给我编程个例子,用于储存单片机掉电后的把数据保存在24c02里面,用keil5编程
时间: 2023-11-13 20:04:12 浏览: 32
好的,下面是一个简单的例子,使用Keil5编写的C语言代码,实现在单片机掉电后将数据保存在24c02 EEPROM中:
```c
#include <reg52.h>
#include <intrins.h>
#define SDA P1_0 // I2C总线数据线
#define SCL P1_1 // I2C总线时钟线
void delay(unsigned int i) // 延时函数
{
while (i--);
}
void i2c_start() // 启动I2C总线
{
SDA = 1;
delay(10);
SCL = 1;
delay(10);
SDA = 0;
delay(10);
SCL = 0;
delay(10);
}
void i2c_stop() // 停止I2C总线
{
SDA = 0;
delay(10);
SCL = 1;
delay(10);
SDA = 1;
delay(10);
}
void i2c_write(unsigned char dat) // 写数据到I2C总线
{
unsigned char i;
for (i = 0; i < 8; i++) {
SDA = (dat & 0x80) >> 7;
dat <<= 1;
delay(10);
SCL = 1;
delay(10);
SCL = 0;
delay(10);
}
SDA = 1;
delay(10);
SCL = 1;
delay(10);
SCL = 0;
delay(10);
}
unsigned char i2c_read() // 从I2C总线读取数据
{
unsigned char i, dat = 0;
SDA = 1;
for (i = 0; i < 8; i++) {
dat <<= 1;
SCL = 1;
delay(10);
dat |= SDA;
SCL = 0;
delay(10);
}
return dat;
}
void eeprom_write(unsigned char addr, unsigned char dat) // 写数据到24c02 EEPROM
{
i2c_start(); // 启动I2C总线
i2c_write(0xa0); // 发送器件地址
i2c_write(addr); // 发送数据地址
i2c_write(dat); // 发送数据
i2c_stop(); // 停止I2C总线
}
unsigned char eeprom_read(unsigned char addr) // 从24c02 EEPROM读取数据
{
unsigned char dat;
i2c_start(); // 启动I2C总线
i2c_write(0xa0); // 发送器件地址
i2c_write(addr); // 发送数据地址
i2c_start(); // 重新启动I2C总线
i2c_write(0xa1); // 发送器件读地址
dat = i2c_read(); // 读取数据
i2c_stop(); // 停止I2C总线
return dat;
}
void main()
{
unsigned char data = 0x55; // 要保存的数据
eeprom_write(0x00, data); // 写入EEPROM
data = eeprom_read(0x00); // 从EEPROM中读取数据
while (1); // 程序循环
}
```
这个例子中,通过使用I2C总线协议,将数据保存在24c02 EEPROM中,以实现在单片机掉电后数据的持久化存储。在主函数中,先将一个数据0x55写入EEPROM中,然后再从EEPROM中读取数据并输出,以验证数据是否成功保存。