以下是我写的I2C总线写E2PROM,然后读取出写入的数据,使P1口赋值为0XAA,但是为什么读出来的数据始终为0XFF呢?看了好多遍了,都不知道哪里出了错,只是
仿真过读数错误,没烧写进
单片机去试
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit SDA_i2c=P2^0;
sbit SCL_i2c=P2^1;
void delay_us()
{ ; ; }
void delay_ms(uchar z)
{
uchar x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void init_i2c() //初始化I2C总线
{
SDA_i2c=1; //SDA拉高
delay_us();
SCL_i2c=1; //SCL拉高
delay_us();
}
void start_i2c() //I2C启动信号
{
SDA_i2c=1; //SDA拉高
delay_us();
SCL_i2c=1; //SCL至高
delay_us();
SDA_i2c=0; //SDA跳低
delay_us();
}
void stop_i2c() //I2C停止信号
{
SDA_i2c=0; //SDA置低
delay_us();
SCL_i2c=1; //SCL至高
delay_us();
SDA_i2c=1; //SDA跳高
delay_us();
}
void respond_i2c() //I2C应答信号
{
uchar i;
SCL_i2c=1;
delay_us();
while((SDA_i2c==1)&&(i<250))
i++;
SCL_i2c=0;
delay_us();
SDA_i2c=1;
delay_us();
}
void write_i2cByte(uchar dat) //I2C写字节
{
uchar i,temp;
temp=dat;
SCL_i2c=0;
delay_us();
for(i=0;i<8;i++)
{
temp=temp<<1;
SCL_i2c=0;
delay_us();
SDA_i2c=CY;
delay_us();
SCL_i2c=1;
delay_us();
}
SCL_i2c=0;
delay_us();
SDA_i2c=1;
delay_us();
}
void write_i2cAddressData(uchar address,uchar dat) //在某地址写入某数据
{
start_i2c();
write_i2cByte(0xae);
respond_i2c();
write_i2cByte(address);
respond_i2c();
write_i2cByte(dat);
respond_i2c();
stop_i2c();
}
uchar read_byte() //I2C读字节
{
uchar i,i2c_dat;
SCL_i2c=0;
delay_us();
SDA_i2c=1;
delay_us();
for(i=0;i<8;i++)
{
SCL_i2c=0;
delay_us();
i2c_dat=(i2c_dat<<1)|SDA_i2c;
delay_us();
SCL_i2c=1;
delay_us();
}
return i2c_dat;
}
uchar read_i2cAddress(uchar address) //从某个地址中读出数据
{
uchar date;
start_i2c();
write_i2cByte(0xae);
respond_i2c();
write_i2cByte(address);
respond_i2c();
start_i2c();
write_i2cByte(0xaf);
respond_i2c();
date=read_byte();
stop_i2c();
return date;
}
void main()
{
init_i2c();
write_i2cAddressData(1,0xaa);
delay_ms(100);
P1=read_i2cAddress(1);
while(1);
}
一周热门 更多>