#include <reg52.h>
#define AddWr 0xa0 //器件读写地址
#define AddRd 0xa1
unsigned char a[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F}; //0-10在数码管上的显示
unsigned char b[8]={0x00,0x04,0x08,0x0c,0x10,0x14,0x18,0x1c}; //选择数码管
sbit SDA=P2^0; //模拟I2C数据传送位
sbit SCL=P2^1; //模拟I2C时钟控制位
unsigned char flag=0;
unsigned char num;
void init() //定时器初始化
{
TMOD=0x20; //定时器1工作方式2
TH1=0xfd; //高八位数据不断地重装入低八位
TL1=0xfd;
TR1=1; //定时器中断允许
REN=1; //允许接收
SM0=0; //串口工作方式1
SM1=1;
EA=1; //总中断允许
ES=1; //串口允许中断
}
void Delay(unsigned int t) //延时
{
int i;
for(i=0;i<t;i++) ;
}
void Start_I2C() //启动总线
{
SDA=1;
Delay(1);
SCL=1;
Delay(5);
SDA=0;
Delay(5);
SCL=0;
Delay(5);
}
void Stop_I2C() //停止总线
{
SDA=0;
Delay(1);
SCL=1;
Delay(5);
SDA=1;
Delay(5);
}
void SendByte(unsigned char d) //发送数据
{
unsigned char send;
for(send=0;send<8;send++)
{
if((d<<send)&0x80)
{
SDA=1;
}
else
{
SDA=0;
}
Delay(1);
SCL=1;
Delay(5);
SCL=0;
}
Delay(2);
SDA=1; //应答 条件SCL为高电平时,接收设备将SDA拉低
Delay(2);
SCL=1;
Delay(3);
while(SDA)
{
Delay(1);
}
SCL=0; //SDA线上的数据必须在SCL时钟的高电平保持稳定,只有在SCL为低电平才能改变
Delay(2);
}
unsigned char Write24c02(unsigned char dat) //写
{
Start_I2C();
SendByte(AddWr);
SendByte(0x02);
SendByte(dat);
Stop_I2C();
return(0);
}
void main ()
{
unsigned char i,t;
init();
while(1)
{
ES=0;
num=SBUF;
Write24c02(num);
Delay(100);
for(i=3;i>0;i--)
{
P2=b[i];
t=num%10;
P0=a[t];
Delay(100);
num=num/10;
}
ES=1;
flag=0;
}
}
void ser() interrupt 4 //串口中断
{
RI=0;
flag=1;
}
|