1.原理图部分


2.CubeMx配置I2C


3.参数配置:

4.代码区:
#define ADDR_24LCxx_Write 0xA0
#define ADDR_24LCxx_Read 0xA1
#define ATC256_PAGE_SIZE 64
#define ATC256_PAGE_NUM 512
/*读取设备参数*/
static void DeviceParm_Read_at24c256(void)
{
uint8_t ReadBuffer[ATC256_BUFFER_SIZE] = { 0 };
HAL_StatusTypeDef status = HAL_OK;
device_param_t tDeviceInfo;
memset(&tDeviceInfo, 0 , sizeof(tDeviceInfo));
status = HAL_I2C_Mem_Read(&hi2c1, ADDR_24LCxx_Read, ATC256_DEVICE_SAVE_PAGE_START, I2C_MEMADD_SIZE_16BIT, ReadBuffer, ATC256_BUFFER_SIZE, 0x1000);
printf("Read Ret %d\r\n",status);
memcpy(&tDeviceInfo, ReadBuffer, sizeof(gDeviceInfo));
if(strlen(tDeviceInfo.DeviceSN) != 0)
{
printf("该设备有初始化SN号码[%s]\r\n", tDeviceInfo.DeviceSN);
memcpy(&gDeviceInfo, ReadBuffer, sizeof(gDeviceInfo));
} else {
printf("此设备没有初始化!\r\n");
TcpSetDefaultlDeviceInfo();
}
}
/*写设备参数*/
uint8_t DeviceParm_Save_at24c256(void)
{
uint8_t WriteBuffer[ATC256_BUFFER_SIZE] = { 0 };
uint8_t ReadBuffer[ATC256_BUFFER_SIZE] = { 0 };
HAL_StatusTypeDef status = HAL_OK;
int i =0;
//拷贝数据到缓存区.
memcpy(WriteBuffer, &gDeviceInfo, sizeof(gDeviceInfo));
for(i=0; i<1024/ATC256_PAGE_SIZE; i++) //32 分32次去写 256个 大小 1024 /64 = 16
{
if (HAL_I2C_Mem_Write(&hi2c1, ADDR_24LCxx_Write, ATC256_DEVICE_SAVE_PAGE_START+i*ATC256_PAGE_SIZE, I2C_MEMADD_SIZE_16BIT,&(WriteBuffer[i*ATC256_PAGE_SIZE]),ATC256_PAGE_SIZE, 1000) == HAL_OK)
{
//printf("\r\n Byte %02d to Byte %02d Write OK",i,i+64);
HAL_Delay(5);//写完以后需要延时5ms,这个不能少
}else{
//printf("\r\n Byte %02d to Byte %02d Write Failed",i,i+8);
}
}
//TcpPrintProtolDeviceInfo(gDeviceInfo);
//再读一遍
status = HAL_I2C_Mem_Read(&hi2c1, ADDR_24LCxx_Read, ATC256_DEVICE_SAVE_PAGE_START, I2C_MEMADD_SIZE_16BIT, ReadBuffer, ATC256_BUFFER_SIZE, 0x1000);
printf("Read Ret %d\r\n",status);
if(memcmp(ReadBuffer, WriteBuffer, MAX_DEVICE_PARAM_LEN) == 0)
{
printf("参数写入成功\r\n");
return 1;
} else {
//printf("设备参数 读写不一致,保存失败!\r\n");
FaultDecte_Set_Device_Deatil(DEVICE_FAULT_TYPE_STROGE); //读写参数不一样. 保存参数故障
}
return 0;
}