求助关于郭天翔I2C总线与24c02通讯的例子
时间:10-02
整理:3721RD
点击:
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
bit write=0;
sbit SDA=P2^1;
sbit SCL=P2^0;
sbit dula=P2^2;
sbit wela=P2^3;
uchar sec=0,tcnt=0;
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void delay()
{
;;
}
void delayMs(uint z)
{
uint x,y;
for(x=z;x>0;x--)
{
for(y=110;y>0;y--);
}
}
void i2c_start() //开始信号
{
SDA=1;
delay();
SCL=1;
delay();
SDA=0;
delay();
}
void i2c_stop() //停止
{
SDA=0;
delay();
SCL=1;
delay();
SDA=1;
delay();
}
void i2c_respons() //应答
{
uchar i;
SCL=1;
delay();
while((SDA==1)&&(i<250)) i++;
SCL=0;
delay();
}
void i2c_init() //初始化
{
SDA=1;
delay();
SCL=1;
delay();
}
void write_byte(uchar date) //写一个字节
{
uchar i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;
SCL=0;
delay();
SDA=CY;
delay();
SCL=1;
delay();
}
SCL=0;
delay();
SDA=1;
delay();
}
uchar read_byte() //读一个字节
{
uchar i,k;
SCL=0;
delay();
SDA=1;
delay();
for(i=0;i<8;i++)
{
SCL=1;
delay();
k=(k<<1)|SDA;
SCL=0;
delay();
}
return k;
}
void write_add(uchar address,uchar date)
{
i2c_start();
write_byte(0xa0); //24c02芯片地址1010
i2c_respons();
write_byte(address); //数据存储地址
i2c_respons();
write_byte(date); //写入一个数据
i2c_respons();
i2c_stop();
}
uchar read_add(uchar address)
{
uchar date;
i2c_start();
write_byte(0xa0);
i2c_respons();
write_byte(address);
i2c_respons();
i2c_start();
write_byte(0xa1);
i2c_respons();
date=read_byte();
i2c_stop();
return date;
}
void display(uchar shi,uchar ge)
{
wela=1;
P0=0xfd;
wela=0;
dula=1;
P0=table[ge];
dula=0;
delayMs(5);
wela=1;
P0=0xfe;
wela=0;
dula=1;
P0=table[shi];
dula=0;
delayMs(5);
}
void main()
{
i2c_init();
sec=read_add(2);
if(sec>=100) //防止首次读取出错误数据
{
sec=0;
}
TMOD=0x01; //定时器0方式为1
ET0=1;
EA=1;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
TR0=1;
while(1)
{
display(sec/10,sec%10);
if(write==1)
{
write=0;
write_add(2,sec);
}
}
}
void t0()interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
tcnt++;
if(tcnt==20)
{
tcnt=0;
sec++;
write=1;
if(sec==100)
{
sec=0;
}
}
}
天翔 相关文章: