STM32基于HAL工程硬件I2C读取AT24Cxx数据

STM32基于HAL工程硬件I2C读取AT24Cxx数据


  • ✨申明:本文章仅发表在CSDN网站,任何其他网站,未注明来源,见此内容均为盗链和爬取,请多多尊重和支持原创!
  • 对于文中所提供的相关资源链接将作不定期更换。
  • 本工程使用STM32F103VE+AT24C32实物验证没有问题。
  • ✨说明:本库文件仅支持容量大于2048Bytes(AT24C16)以上型号的读取,如果使用在小于2048Bytes的器件上,数据首尾会对不上。
  • 型号和容量参照:
#define AT24C01		127
#define AT24C02		255
#define AT24C04		511
#define AT24C08		1023
#define AT24C16		2047
#define AT24C32		4095
#define AT24C64	    8191
#define AT24C128	16383
#define AT24C256	32767 

AT24Cxx地址说明

  • AT24C02/C4/C8/C16的I2C地址取决于引脚A0、A1和A2的电平设置,可以有8个不同的地址。以下是每个地址对应的引脚配置:
0b1010000:A0 = 0,A1 = 0,A2 = 0
0b1010001:A0 = 1,A1 = 0,A2 = 0
0b1010010:A0 = 0,A1 = 1,A2 = 0
0b1010011:A0 = 1,A1 = 1,A2 = 0
0b1010100:A0 = 0,A1 = 0,A2 = 1
0b1010101:A0 = 1,A1 = 0,A2 = 1
0b1010110:A0 = 0,A1 = 1,A2 = 1
0b1010111:A0 = 1,A1 = 1,A2 = 1
  • 如果引脚A0-A1-A2都接地,则AT24Cxx的I2C地址为0b1010000(或0x50)。
  • 测试AT24C32读取的信息串口打印:
    STM32基于HAL工程硬件I2C读取AT24Cxx数据_第1张图片

STM32CubeMX工程配置

  • 使能一个I2C接口。(如果选择I2C2,需要在AT24Cxx.h,修改相关宏定义(#define EEPROM_I2C hi2c1)。)
    STM32基于HAL工程硬件I2C读取AT24Cxx数据_第2张图片
  • 使能一个串口,用于调试信息输出。
    STM32基于HAL工程硬件I2C读取AT24Cxx数据_第3张图片
    • printf调试信息输出,需要在usart.c文件中添加printf重映射代码,以及Keil设置勾选MicroLib选项:
#include "stdio.h"
/*可调用printf*/
int fputc(int ch,FILE *f)
{
    /*&huart1指的是串口1,如果用别的串口就修改数字*/
    HAL_UART_Transmit(&huart1 , (uint8_t *)&ch , 1 , 1000);
    return ch;
}

时钟源根据个人具体的STM32型号自己配置。

AT24Cxx驱动代码

  • AT24Cxx.c文件
/*
 * AT24Cxx.c
 *
 */
#include "AT24Cxx.h"


static unsigned eeprom_address = EEPROM_ADDRESS << 1;

static unsigned inpage_addr_mask = EEPROM_PAGESIZE - 1;

static HAL_StatusTypeDef AT24Cxx_WriteReadEEPROM(unsigned address, const void *src, unsigned len, bool write);
static unsigned size_to_page_end(unsigned addr);

HAL_StatusTypeDef AT24Cxx_IsConnected(void)
{
    return HAL_I2C_IsDeviceReady(&EEPROM_I2C, eeprom_address, 1, EEPROM_TIMEOUT);
}

HAL_StatusTypeDef AT24Cxx_ReadEEPROM(unsigned address, const void *src, unsigned len)
{
    return AT24Cxx_WriteReadEEPROM(address, src, len, false);
}

HAL_StatusTypeDef AT24Cxx_WriteEEPROM(unsigned address, const void *src, unsigned len)
{
    return AT24Cxx_WriteReadEEPROM(address, src, len, true);
}

static HAL_StatusTypeDef AT24Cxx_WriteReadEEPROM(unsigned address, const void *src, unsigned len, bool write)
{
    uint8_t *pdata = (uint8_t *) src;
    unsigned portion;
    unsigned max_portion;
    HAL_StatusTypeDef result = HAL_OK;
    max_portion = size_to_page_end(address); //发送器件地址0XA0,写数据
    while (len != 0 && result == HAL_OK)
    {
        portion = len;

        if (portion > max_portion)
        {
            portion = max_portion;
        }

        if (write)
        {
            result = HAL_I2C_Mem_Write(&EEPROM_I2C,
                                       eeprom_address,
                                       address,
                                       I2C_MEMADD_SIZE_16BIT,
                                       pdata,
                                       portion,
                                       EEPROM_TIMEOUT);
        }
        else
        {
            result = HAL_I2C_Mem_Read(&EEPROM_I2C,
                                      eeprom_address,
                                      address,
                                      I2C_MEMADD_SIZE_16BIT,
                                      pdata,
                                      portion,
                                      EEPROM_TIMEOUT);
        }


        len     -= portion;
        address += portion;
        pdata   += portion;


        max_portion = EEPROM_PAGESIZE;

        if (write)
        {
            HAL_Delay(EEPROM_WRITE);
        }
        else
        {
            HAL_Delay(EEPROM_WRITE / 2);
        }
    }

    return result;
}


static unsigned size_to_page_end(unsigned addr)
{
    return (~addr & inpage_addr_mask) + 1;
}

  • AT24Cxx.h文件
/*
 * AT24Cxx.h
 *
 */

#ifndef AT24CXX_H_
#define AT24CXX_H_

#include "stm32f1xx_hal.h"
#include "stdbool.h"

#define	EEPROM_I2C			hi2c1
#define EEPROM_ADDRESS		0x50
#define EEPROM_PAGESIZE		128
#define EEPROM_WRITE		10					//time to wait in ms
#define EEPROM_TIMEOUT		5 * EEPROM_WRITE	//timeout while writing


extern I2C_HandleTypeDef EEPROM_I2C;

HAL_StatusTypeDef AT24Cxx_IsConnected(void);
HAL_StatusTypeDef AT24Cxx_ReadEEPROM(unsigned address, const void* src, unsigned len);
HAL_StatusTypeDef AT24Cxx_WriteEEPROM(unsigned address, const void* src, unsigned len);

#endif /* AT24CXX_H_ */

main主程序代码

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "AT24Cxx.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define AT24Cxx_ADDRESS ((uint16_t)0xA0)
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint8_t Buffer[] = "Hi!STM32F103VE 9527 Perseverance";
#define countof(a) (sizeof(a) / sizeof(*(a)))
#define BufferSize1     (countof(Buffer)-1)
uint8_t Read_Buffer[BufferSize1];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_I2C1_Init();
    MX_USART1_UART_Init();
    /* USER CODE BEGIN 2 */
    uint32_t TimerUART = HAL_GetTick();
    if (AT24Cxx_IsConnected() == HAL_OK)
    {
        printf("AT24Cxx Read success \r\n");
        AT24Cxx_WriteEEPROM((AT24Cxx_ADDRESS), Buffer, BufferSize1);
    }
    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
        /* USER CODE END WHILE */

        /* USER CODE BEGIN 3 */
        if ((HAL_GetTick() - TimerUART) > 2500)
        {
            AT24Cxx_ReadEEPROM((AT24Cxx_ADDRESS), Read_Buffer, BufferSize1);

            printf("Read_Date=%s\r\n",Read_Buffer );
            TimerUART = HAL_GetTick();
            HAL_GPIO_TogglePin(GPIOE, LED_Pin);
        }
    }
    /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                  | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
    {
        Error_Handler();
    }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
    /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

工程源码

  • ✨申明:本文章仅发表在CSDN网站,任何其他网站,未注明来源,见此内容均为盗链和爬取,请多多尊重和支持原创!
  • 对于文中所提供的相关资源链接将作不定期更换。

链接: https://pan.baidu.com/s/1K5Fky_L2dFH8KHPfc1ABPw
提取码: i2g9

你可能感兴趣的:(stm32,STM32CubeIDE,AT24C32)