STM32CubeMX系列教程9:内部集成电路(I2C)
在mian.c文件前面声明两个输出存储读写数据,宏定义E2PROM读写地址以及缓存数据长度。
/* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ #define ADDR_24LCxx_Write 0xA0 #define ADDR_24LCxx_Read 0xA1 #define BufferSize 0x100 uint8_t WriteBuffer[BufferSize],ReadBuffer[BufferSize]; uint16_t i; /* USER CODE END PV */
在mian()函数里面添加应用程序读写E2PROM。
/* USER CODE BEGIN 2 */ printf("\r\n***************I2C Example*******************************\r\n"); for(i=0; i<256; i++) WriteBuffer[i]=i; /* WriteBuffer init */ /* wrinte date to EEPROM */ if(HAL_I2C_Mem_Write(&hi2c1, ADDR_24LCxx_Write, 0, I2C_MEMADD_SIZE_8BIT,WriteBuffer,BufferSize, 0x10) == HAL_OK) printf("\r\n EEPROM 24C02 Write Test OK \r\n"); else printf("\r\n EEPROM 24C02 Write Test False \r\n"); /* read date from EEPROM */ HAL_I2C_Mem_Read(&hi2c1, ADDR_24LCxx_Read, 0, I2C_MEMADD_SIZE_8BIT,ReadBuffer,BufferSize, 0x10); for(i=0; i<256; i++) printf("0x%02X ",ReadBuffer[i]); if(memcmp(WriteBuffer,ReadBuffer,BufferSize) == 0 ) /* check date */ printf("\r\n EEPROM 24C02 Read Test OK\r\n"); else printf("\r\n EEPROM 24C02 Read Test False\r\n"); /* USER CODE END 2 */
程序中先初始化写数据缓存。然后调用HAL_I2C_Mem_Write()函数将数据写入E2PROM中。根据函数返回值判断写操作是否正确。在I2C中可以找到内存写函数说明。第一个参数为I2C操作句柄。第二个参数为E2PROM的写操作设备地址。第三个参数为内存地址,第二个参数为内存地址长度,E2PROM内存长度为8bit,第四个参数为数据缓存的起始地址,第五个参数为传输数据的大小,第六个参数为操作超时时间。
/** * @brief Write an amount of data in blocking mode to a specific memory address * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress: Target device address * @param MemAddress: Internal memory address * @param MemAddSize: Size of internal memory address * @param pData: Pointer to data buffer * @param Size: Amount of data to be sent * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, <span style="font-size: 9pt; line-height: 16.8px; widows: auto;">uint8_t *pData, uint16_t Size, uint32_t Timeout)</span>
调用HAL_I2C_Mem_Read()函数读取E2PROM中刚才写入的数据。
HAL_I2C_Mem_Read()函数描述如下。第一个参数为I2C操作句柄。第二个参数为E2PROM的读操作设备地址。第三个参数为内存地址,第二个参数为内存地址长度,第四个参数为读取数据存储的起始地址,第五个参数为传输数据的大小,第六个参数为操作超时时间。
/** * @brief Read an amount of data in blocking mode from a specific memory address * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains * the configuration information for the specified I2C. * @param DevAddress: Target device address * @param MemAddress: Internal memory address * @param MemAddSize: Size of internal memory address * @param pData: Pointer to data buffer * @param Size: Amount of data to be sent * @param Timeout: Timeout duration * @retval HAL status */ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)