蓝桥杯比赛倒计时第8天
今天写的是蓝桥杯模块————AT24C02,主要讲一下如何对一个整型的数据进行存储,相信各位省一选手对一个char型的数组读取已经了如指掌了,所以就不再这里进行讲解了。
一、eeprom写入函数
void write_myepprom(unsigned char addre,unsigned char dat)
{
I2CStart();
I2CSendByte(0xa0);
I2CWaitAck();
I2CSendByte(addre);
I2CWaitAck();
I2CSendByte(dat);
I2CWaitAck();
I2CStop();
Delay5ms();
}
其中延时5ms的作用是保证数据写入完成,不加可能会 导致数据写入出错。
二、eeprom读取函数
unsigned char read_myepprom(unsigned char addre)
{
unsigned char value_c02;
I2CStart();
I2CSendByte(0xa0);
I2CWaitAck();
I2CSendByte(addre);
I2CWaitAck();
I2CStart();
I2CSendByte(0xa1);
I2CWaitAck();
value_c02 = I2CReceiveByte();
I2CSendAck(1);
I2CStop();
Delay5ms();
return value_c02;
}
延时函数原理同上
三、将一个int数据写入eeprom
办法:将一个int数据进行拆分,分别取高位和低位,然后分别进行存取。其操作办法如下
write_myepprom(0x01,count >> 8);//将int型数据count左移8位,移除低位
write_myepprom(0x02,count);//由于24C02只能存储8位数据,自动舍弃高位
四、将读取的数据在重新合成一个int型数据
其办法如下
分别读取高位和低位
count_h = read_myepprom(0x01);
count_l = read_myepprom(0x02);
count_smg = count_h * 256 + count_l;
五、测试程序
#include "reg52.h"
#include "iic.h"
#include "DisplaySMG.h"
#include "intrins.h"
code unsigned char Seg_Table[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82,0xf8,
0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86,0x8e };
code unsigned char Seg_DOtTable[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};
/*存入一个整型数据,上电自动读出*/
unsigned int count = 9999;
unsigned char count_h = 0;
unsigned char count_l = 0;
unsigned int count_smg = 0;
void Delay5ms() //@12.000MHz
{
unsigned char i, j;
i = 59;
j = 90;
do
{
while (--j);
} while (--i);
}
unsigned char read_myepprom(unsigned char addre)
{
unsigned char value_c02;
I2CStart();
I2CSendByte(0xa0);
I2CWaitAck();
I2CSendByte(addre);
I2CWaitAck();
I2CStart();
I2CSendByte(0xa1);
I2CWaitAck();
value_c02 = I2CReceiveByte();
I2CSendAck(1);
I2CStop();
Delay5ms();
return value_c02;
}
void write_myepprom(unsigned char addre,unsigned char dat)
{
I2CStart();
I2CSendByte(0xa0);
I2CWaitAck();
I2CSendByte(addre);
I2CWaitAck();
I2CSendByte(dat);
I2CWaitAck();
I2CStop();
Delay5ms();
}
void DisplaySMG_Info()
{
DispalySMG_Bit(4,Seg_Table[count_smg / 1000]);
DispalySMG_Bit(5,Seg_Table[count_smg / 100 % 10]);
DispalySMG_Bit(6,Seg_Table[count_smg / 10 % 10]);
DispalySMG_Bit(7,Seg_Table[count_smg % 10]);
}
void main()
{
write_myepprom(0x01,count >> 8);
write_myepprom(0x02,count);
count_h = read_myepprom(0x01);
count_l = read_myepprom(0x02);
count_smg = count_h * 256 + count_l;
while(1)
{
DisplaySMG_Info();
}
}
提示:以上为个人观点,仅供参考,入大佬们有更好的想法,可以评论区评论。后续会继续更新其他模块,敬请关注。