最近两天在学习24c08的程序编写,现在模仿着编了个读写的程序,就是把一个数写入24C08,然后读出来显示到数码管上,哈哈,写完也算是对I2C总线有了个初步的了解。。
#include<at89x52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit SCL="P2"^6;
sbit SDA="P2"^7;
uchar code displaycode[]={0XC0,0XF9,0XA4,0XB0,0X99,0X92,0X82,0XF8,0X80,0X90};
uchar code displaybit[]={0xfe,0xfd,0xfb,0xf7};
uchar displaybuf[3];
void delayX2us(uchar x) //微秒延时
{
while(--x);
}
void delayXms(uchar x) //毫秒延时
{
uchar i;
while(x--)
{
for(i=250;i>0;i--)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
}
}
void start ()
{
SDA=1;
delayX2us(2);
SCL=1;
delayX2us(2);
SDA=0;
delayX2us(2);
}
void stop ()
{
SDA=0;
delayX2us(2);
SCL=1;
delayX2us(2);
SDA=1;
delayX2us(2);
}
void init()
{
SCL=1;
delayX2us(2);
SDA=1;
delayX2us(2);
}
void responds()
{
uchar i;
i=0;
SCL=1;
delayX2us(2);
while(SDA==1&&i<200)
i++;
SCL=0;
delayX2us(2);
}
void write_dat (uchar dat) //写一个字节
{
uchar i;
for(i=0;i<8;i++)
{
SCL=0;
delayX2us(2);
SDA=(bit)(dat&0x80);
delayX2us(2);
SCL=1;
delayX2us(2);
SCL=0;
delayX2us(2);
dat<<=1;
}
SDA=1;
delayX2us(2);
}
void write(uchar dat,uchar add) // 写一个字节dat到地址add
{
start();
write_dat(0xa0);
responds();
write_dat(add);
responds();
write_dat(dat);
responds();
stop();
}
uchar read_dat () //读一个字节
{
uchar i;
uchar dat;
bit j;
for (i=0;i<8;i++)
{
dat<<=1;
SCL=0;
j=SDA;
delayX2us(2);
SCL=1;
if(j==1)
{
dat|=0x01;
}
SCL=0;
}
return dat;
}
uchar read (uchar add) //从地址add中读取一个字节
{
uchar dat;
start();
write_dat(0xa0);
responds();
write_dat(add);
responds();
start();
write_dat(0xa1);
responds();
dat=read_dat();
delayX2us(2);
stop();
return dat;
}
void display(uchar dat) //显示程序
{
uchar bai,shi,ge,i;
bai=dat/100;
shi=dat%100/10;
ge=dat%10;
displaybuf[0]=bai;
displaybuf[1]=shi;
displaybuf[2]=ge;
for(i=0;i<3;i++)
{
P0=displaycode[displaybuf];
P1=displaybit;
delayX2us(5);
P1=0xff;
}
}
void main ()
{
uchar dat,add,k;
dat=212;
add=2;
init();
write(dat,add);
delayXms(1000);
k=read(add);
while(1)
{
display(k);
}
}
用户377235 2012-12-27 10:30
用户580322 2009-7-28 15:23