一,STM32CubeMx配置
1,配置RCC 2,配置SYS 3,配置时钟 4,配置工程名,存放地址 5,选择库文件,生成工程 6,配置IIC,保持默认就行 7,生成代码
二,keil代码
AT24C02默认读地址为0xA0,写地址为0xA1
1,储存,读取一个字节
使用函数:
HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout);
HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout);
实例:
uint8_t value1=123;
uint8_t value2;
int main(void)
{
printf("-------w/r one bit:-------\r\n");
HAL_I2C_Master_Transmit( &hi2c1,0xA0,&value1,1,100);
HAL_Delay(500);
HAL_I2C_Master_Receive(&hi2c1, 0xA1, &value2, 1,100);
HAL_Delay(500);
while(1)
{
}
}
2,储存,读取一个字符型数组
使用函数:
HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout);
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);
实例:
#include "string.h"
uint8_t value3[]={"LEN"};
uint8_t value4[4];
int main(void)
{
printf("-------w/r one arrays:-------\r\n");
HAL_I2C_Mem_Write(&hi2c1, 0xA0,0, I2C_MEMADD_SIZE_8BIT,value3,strlen((char*)value3), 100);
HAL_Delay(500);
HAL_I2C_Mem_Read(&hi2c1, 0xA1, 0, I2C_MEMADD_SIZE_8BIT,value4,strlen((char*)value3), 100);
HAL_Delay(500);
printf("value4: ");
for(i=0;i<4;i++)
printf("%c",value4[i]);
printf("\r\n");
while(1)
{
}
}
3,储存,读取一个实数(int ,float)
#include "string.h"
#include <stdlib.h>
uint16_t i;
float flt=445.1;
float out=0;
int main(void)
{
printf("-------w/r one float:-------\r\n");
i=AT24_Writefloat(6,flt);
HAL_Delay(500);
printf("fl1oat: %g\r\n",AT24_Readfloat(6,i));
while(1)
{
}
}
自定义函数
uint8_t AT24_Writefloat(uint16_t address,float array)
{
uint16_t add;
uint8_t WriteBuffer[32];
add=address;
sprintf((char*)WriteBuffer,"%g",array);
if(HAL_I2C_Mem_Write(&hi2c1, 0xA0, add, I2C_MEMADD_SIZE_8BIT,WriteBuffer,strlen((char*)WriteBuffer), 100)==HAL_OK)
return strlen((char*)WriteBuffer);
else return 0;
}
float AT24_Readfloat(uint16_t address,uint16_t FloatLen)
{
uint8_t ReadBuffer[32];
float FloatValue;
if(HAL_I2C_Mem_Read(&hi2c1, 0xA1, address, I2C_MEMADD_SIZE_8BIT,ReadBuffer,FloatLen, 100)==HAL_OK)
FloatValue = atof((char*)ReadBuffer);
return (float)FloatValue;
}
结果:
|