单片机源程序如下:- #include "reg51.h"
- #define uint unsigned int
- #define uchar unsigned char
- sbit SDA = P2^0;
- sbit SCL = P2^1;
- /*共阳数码管的4位控制端口*/
- sbit LSA = P2^2;
- sbit LSB = P2^3;
- sbit LSC = P2^4;
- sbit LSD = P2^5;
- uchar codeLED[10]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
- uchar num = 25; //存放数据
- uchar display_num = 0; //读出数据
- uchar wei[4] = {0}; //LED数码管的4位的显示值
- void Delay_10us(void)
- {
- unsignedchar a = 0;
- unsigned char b = 0;
- for(b=1;b>0;b--)
- {
- for(a=2;a>0;a--);
- }
- }
- void IIC_Start(void)
- {
- SDA=1;
- Delay_10us();
- SCL=1;
- Delay_10us();
- SDA=0;
- Delay_10us();
- SCL=0;
- Delay_10us();
- }
- void IIC_Stop(void)
- {
- SDA=0;
- Delay_10us();
- SCL=1;
- Delay_10us();
- SDA=1;
- Delay_10us();
- }
- unsigned char IIC_SendByte(unsigned chardat)
- {
- unsignedchar a = 0;
- unsigned char b = 0;
- for(a=0;a<8;a++)
- {
- SDA= dat >> 7;
- dat= dat << 1;
- Delay_10us();
- SCL= 1;
- Delay_10us();
- SCL= 0;
- Delay_10us();
- }
- SDA= 1;
- Delay_10us();
- SCL= 1;
- while(SDA)
- {
- b++;
- if(b>200)
- {
- SCL= 0;
- Delay_10us();
- return0;
- }
- }
- SCL= 0;
- Delay_10us();
- return1;
- }
- unsigned char IIC_ReadByte(void)
- {
- unsignedchar a = 0;
- unsigned char dat = 0;
- SDA= 1;
- Delay_10us();
- for(a=0;a<8;a++)
- {
- SCL= 1;
- Delay_10us();
- dat<<= 1;
- dat|= SDA;
- Delay_10us();
- SCL= 0;
- Delay_10us();
- }
- returndat;
- }
- void AT24C02_Write(unsigned charaddr,unsigned char dat)
- {
- IIC_Start();
- IIC_SendByte(0xa0);
- IIC_SendByte(addr);
- IIC_SendByte(dat);
- IIC_Stop();
- }
- unsigned char AT24C02_Read(unsigned charaddr)
- {
- unsigned char display = 0;
- IIC_Start();
- IIC_SendByte(0xa0);
- IIC_SendByte(addr);
- IIC_Start();
- IIC_SendByte(0xa1);
- display = IIC_ReadByte();
- IIC_Stop();
- return display;
- }
- /*延时函数*/
- void Delay(uint i)
- {
- while(i--);
- }
- /*数据处理*/
- void Data_Deal(void)
- {
- wei[0] = display_num / 1000;
- wei[1] = display_num % 1000 / 100;
- wei[2] = display_num % 1000 % 100 / 10;
- wei[3] = display_num % 1000 % 100 % 10;
- }
- /*显示函数*/
- void Display(void)
- {
- uchar i = 0;
- for(i=0;i<4;i++)
- {
- switch(i)
- {
- case 0: LSA=0; LSB=1; LSC=1; LSD=1; break; //显示第1位
- case 1: LSA=1; LSB=0; LSC=1; LSD=1; break; //显示第2位
- case 2: LSA=1; LSB=1; LSC=0; LSD=1; break; //显示第3位
- case 3: LSA=1; LSB=1; LSC=1; LSD=0; break; //显示第4位
- }
- P0 = LED[wei[ i]]; //发送段码
- Delay(100);
- }
- }
- void main(void)
- {
- while(1)
- {
- AT24C02_Write(1,num); //保存地址:1 保存内容:num
- display_num = AT24C02_Read(1); //读取地址1中的num
- Data_Deal(); //数据处理
- Display(); //数码管显示
- }
- }
复制代码
|