首先点开软件包里面的外围库与驱动程序,再点开AT24CXX驱动库。
第1步 在board.h打开#define BSP_USING_I2C1,并且修改对应的IO口。例如本人开发板的BSP_I2C1_SCL_PIN 为PB10,BSP_I2C1_SDA_PIN 为PB11(根据自己的硬件去进行修改)。
第2步 在 #include <at24cxx.h>修改芯片宏定义,本人开发板是at24c02(根据自己的硬件去进行修改)。
#include <rtthread.h>
#include <rtdevice.h>
#include <at24cxx.h>
#define AT24CXX_ADDR (0xA0 >> 1) //A0 A1 A2 connect GND
#define I2C_NAME "i2c1"
at24cxx_device_t at24c02_dev ;
void at24c02_Config(void)
{
at24c02_dev = at24cxx_init(I2C_NAME,AT24CXX_ADDR);
if(at24c02_dev == RT_NULL)
{
rt_kprintf("at24cxx_init failed\n");
return ;
}
}
void at24c02_WriteData(rt_uint32_t writeAddr , rt_uint8_t *data,rt_uint32_t len)
{
rt_err_t res ;
res = at24cxx_check(at24c02_dev);
if(res == RT_ERROR)
{
rt_kprintf("at24cxx_check error!\n");
return ;
}
res = at24cxx_write(at24c02_dev, writeAddr, data, len);
if(res == RT_ERROR)
{
rt_kprintf("at24cxx_write failed!\n");
return ;
}
}
void at24c02_ReadData(rt_uint32_t readAddr , rt_uint8_t *data,rt_uint32_t len)
{
rt_err_t res ;
res = at24cxx_check(at24c02_dev);
if(res == RT_ERROR)
{
rt_kprintf("at24cxx_check error!\n");
return ;
}
res = at24cxx_read(at24c02_dev, readAddr, data, len);
if(res == RT_ERROR)
{
rt_kprintf("at24cxx_read failed!\n");
return ;
}
}
在main函数调用上面函数即可
//rt_uint8_t buf[10] = {'\0'};
//at24c02_Config(); //at24c02
//at24c02_WriteData(0,(rt_uint8_t *)"world",5);
//rt_thread_mdelay(2000);
//at24c02_ReadData(0,buf,5);
//rt_kprintf("buf == %s\n",buf);
通过用户层代码at24c02_WriteData(0,(rt_uint8_t *)“world”,5);将数据写入EEPROM,再通过 at24c02_ReadData(0,buf,5);将数据读出来,再通过串口将数据打印到串口助手显示,具体的结果如下图所示。