仿真原理图如下(proteus仿真工程文件可到本帖附件中下载)
单片机源程序如下:
- #include <REGX52.H>
- #include "LCD1602.h"
- #include "Delay.h"
- #include "AT24C02.h"
- #include "Key.h"
- unsigned char KeyNum;
- unsigned int Num;
- void main()
- {
- LCD_Init();
- LCD_ShowNum(1,1,Num,5);
- while(1)
- {
- KeyNum=Key();
- if(KeyNum==1) //K1按键,Num自增
- {
- Num++;
- LCD_ShowNum(1,1,Num,5);
- }
- if(KeyNum==2) //K2按键,Num自减
- {
- Num--;
- LCD_ShowNum(1,1,Num,5);
- }
- if(KeyNum==3) //K3按键,向AT24C02写入数据
- {
- AT24C02_WriteByte(0,Num%256);
- Delay(5);
- AT24C02_WriteByte(1,Num/256);
- Delay(5);
- LCD_ShowString(2,1,"Write OK");
- Delay(1000);
- LCD_ShowString(2,1," ");
- }
- if(KeyNum==4) //K4按键,从AT24C02读取数据
- {
- Num=AT24C02_ReadByte(0);
- Num|=AT24C02_ReadByte(1)<<8;
- LCD_ShowNum(1,1,Num,5);
- LCD_ShowString(2,1,"Read OK ");
- Delay(1000);
- LCD_ShowString(2,1," ");
- }
- }
- }
复制代码- #include <REGX52.H>
- #include "I2C.h"
- #define AT24C02_ADDRESS 0xA0
- /**
- * @brief AT24C02写入一个字节
- * @param WordAddress 要写入字节的地址
- * @param Data 要写入的数据
- * @retval 无
- */
- void AT24C02_WriteByte(unsigned char WordAddress,Data)
- {
- I2C_Start();
- I2C_SendByte(AT24C02_ADDRESS);
- I2C_ReceiveAck();
- I2C_SendByte(WordAddress);
- I2C_ReceiveAck();
- I2C_SendByte(Data);
- I2C_ReceiveAck();
- I2C_Stop();
- }
- /**
- * @brief AT24C02读取一个字节
- * @param WordAddress 要读出字节的地址
- * @retval 读出的数据
- */
- unsigned char AT24C02_ReadByte(unsigned char WordAddress)
- {
- unsigned char Data;
- I2C_Start();
- I2C_SendByte(AT24C02_ADDRESS);
- I2C_ReceiveAck();
- I2C_SendByte(WordAddress);
- I2C_ReceiveAck();
- I2C_Start();
- I2C_SendByte(AT24C02_ADDRESS|0x01);
- I2C_ReceiveAck();
- Data=I2C_ReceiveByte();
- I2C_SendAck(1);
- I2C_Stop();
- return Data;
- }
复制代码
仿真程序51hei附件下载:
AT24C02.zip
(139.69 KB, 下载次数: 42)
|