我的单片机芯片是 AT89S52 .
以下程序是想通过I2C总线与24C08存储器通信。首先对24C08存储器写入数据,再向24C08存储器读出数据,以该数据来点亮LED灯。
程序如下:
#include<reg52.h>
#include <intrins.h>
sbit scl=P3^4;
sbit sda=P3^5;
void delay()
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
void start()
{
sda=1;
scl=1;
delay();
sda=0;
delay();
scl=0;
}
void stop()
{
sda=0;
delay();
scl=1;
delay();
sda=1;
delay();
}
void ask()
{ unsigned char i;
sda=1;
delay();
scl=1;
delay();
while((sda==1)&&(i<250))i++;
scl=0;
delay();
}
void write(unsigned char y)
{ unsigned char i;
for(i=0;i<8;i++)
{
y=y<<1;
sda=CY;
delay();
scl=1;
delay();
scl=0;
delay();
}
}
unsigned char read()
{ unsigned char t=0;
unsigned char X;
unsigned char i;
for(i=0;i<8;i++)
{
scl=1;
delay();
X=sda;
delay();
t=t<<1;
t=X|t;
scl=0;
delay();
}
return t;
}
void main()
{
sda=1;
scl=1;
start();
write(0xa0);
ask();
write(3);
ask();
write(0x7f);
ask();
stop();
delay();
start();
write(0xa0);
ask();
write(3);
ask();
start();
write(0xa1);
ask();
P0=read();
delay();
stop();
while(1);
}
最终结果LED灯 P0.0、P0.1不亮,P0.2~0.7都亮,显然结果错误。我写入的数据是 0x7f 而读出来确不是。哪位高手帮忙解答一下?感激不尽!