初级会员
- 积分
- 82
- 金钱
- 82
- 注册时间
- 2018-7-10
- 在线时间
- 11 小时
|
#include <reg52.h>
//SCL=0 SDA才可以变化
sbit SDA=P2^0 ;
sbit SCL=P2^1 ;
sbit DU = P2^6;//数码管段选
sbit WE = P2^7;//数码管段选
typedef unsigned char uchar;
bit AckFlag;
uchar num;
#define EEPROM_ADDS 0xa0
#define SEND 0
#define RESIVE 1
uchar code SMGduan[]= {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F,};
//数码管位选码
uchar code SMGwei[] = {0xfe, 0xfd, 0xfb};
void timer0Init()
{
EA = 1; //打开总中断
ET0 = 1;//打开定时器0中断
TR0 = 1; //启动定时器0
TMOD |= 0X01; //定时器工作模式1,16位定时模式
TH0 = 0xED;
TL0 = 0xFF; //定时5ms
}
void display(uchar i)
{
static uchar wei;
P0 = 0XFF;//清除断码
WE = 1;//打开位选锁存器
P0 = SMGwei[wei];
WE = 0;//锁存位选数据
switch(wei)
{
case 0: DU = 1; P0 = SMGduan[i / 100]; DU = 0; break;
case 1: DU = 1; P0 = SMGduan[i % 100 / 10]; DU = 0; break;
case 2: DU = 1; P0 = SMGduan[i % 10]; DU = 0; break;
}
wei++;
if(wei == 3)
wei = 0;
}
void delay(void) //误差 -0.074652777778us 5.5us
{
unsigned char a;
for(a=1;a>0;a--);
}
void start_()
{
SCL=1;
SDA=1;
delay();
SDA=0;
delay();
}
void stop_()
{
SCL=0;
SDA=0;
SCL=1;
delay();
SDA=1;
delay();
}
bit ReadACK()
{
SCL = 0;//拉低时钟总线,允许从机控制SDA
SCL = 1;//拉高,读SDA
delay();
if(SDA)//NOACK
{
SCL = 0;
return(1);//返回1
}
else//ACK
{
SCL = 0;
return(0);//返回0
}
}
void SendACK(bit i)
{
SCL = 0;//拉低时钟总线,允许主机控制SDA
if(i) //发非应答
SDA = 1;
else //发应答
SDA = 0;
SCL = 1; //拉高总线,让从机读SDA
delay();//保持5us
SCL = 0; //拉低时钟总线,允许SDA释放
SDA = 1;//释放数据总线
}
void send_byte(unsigned char DATA)
{
unsigned char i;
for(i=0;i<8;i++)
{
SCL=0;
if(DATA & 0x80) SDA=1;
else SDA=0;
SCL=1;
DATA <<=1;
}
SCL=0;
SDA=1;
}
uchar resive_byte()
{
uchar i, DAT;
for(i=0; i<8; i++)//分别读8次,每次读一位
{
DAT <<= 1; //数据左移1位,准备接收一位
SCL = 0; //拉低时钟总线,允许从机控制SDA变化
SCL = 1; //拉高时钟总线,读取SDA上的数据
if(SDA)
DAT |= 0X01;//为1则写1,否则不行执行写1,通过左移补0
}
return(DAT); //返回读出的数据
}
//uchar resive_byte()
//{
//unsigned char i,DATA;
//for(i=0;i<8;i++)
//{
//SCL=0;
//SCL=1;
//DATA |=SDA;
//DATA <<=DATA;
//}
//return DATA;
//}
void delay1(uchar z)
{
uchar x,y;
for(x = z; x > 0; x--)
for(y = 114; y > 0 ; y--);
}
void main()
{
timer0Init();
EA=0;
start_();
send_byte(EEPROM_ADDS + SEND);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
send_byte(3);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
send_byte(188);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
stop_();
start_();
send_byte(EEPROM_ADDS + SEND);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
send_byte(3);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
start_();
send_byte(EEPROM_ADDS + RESIVE);
if(ReadACK())//读从机应答
AckFlag = 1;
else
AckFlag = 0;
num=resive_byte();
SendACK(1);
stop_();
EA=1;
while(1);
}
void timer0() interrupt 1
{
TH0 = 0xED;
TL0 = 0xFF; //定时5ms
display(num); //数码管显示函数
}
|
|