proteus仿真:I2c总线和EEPROM2404的读写
扫描二维码
随时随地手机看文章
仿真电路图:
仿真程序:
#include
#include
#define uchar unsigned char
#define uint unsigned int
sbit SCL=P1^0;
sbit SDA=P1^1;
void delay(void)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
void InitI2C(void)
{
SDA = 1;
SCL = 1;
}
void I2CStart(void)
{
SDA=1;
delay();
SCL=1;
delay();
SDA=0;
delay();
SCL=0;
}
void I2CStop(void)
{
SCL=0;
delay();
SDA=0;
delay();
SCL=1;
delay();
SDA=1;
delay();
}
void I2CSend(uchar byte)
{
uchar mask;
uchar i,j;
mask=0x80;
for(i=0;i<8;i++)
{
SCL=0;
delay();
if((mask & byte)==0)
{
SDA=0;
}
else
{
SDA=1;
}
mask>>=1;
delay();
SCL=1;
delay();
}
SCL=0;
SDA=1;
delay();
SCL=1;
j=SDA;
delay();
SCL=0;
}
void write_eeprom(uchar addr, uchar databyte)
{
I2CStart();
I2CSend(0xa0);
I2CSend(addr);
I2CSend(databyte);
I2CStop();
}
uchar I2CRead(void)
{
uchar byte;
uchar i;
byte = 0;
for(i = 0; i < 8; i++)
{
SCL = 0;
SDA = 1;
delay();
SCL = 1;
delay();
byte <<= 1;
if(SDA == 1)
{
byte |= 0x01;
}
delay();
}
SCL = 0;
SDA = 1;
delay();
SCL = 1;
delay();
SCL = 0;
return byte;
}
uchar read_eeprom(uchar addr)
{
uchar databyte;
I2CStart();
I2CSend(0xa0);
I2CSend(addr);
I2CStart();
I2CSend(0xa1);
databyte = I2CRead();
I2CStop();
return databyte;
}
main()
{
uchar addr=0x00,databyte=0xaa;
uchar c=0;
uint i;
InitI2C();
while(1)
{
write_eeprom(addr,databyte);
for(i = 0; i < 1000; i++)
{
delay();
}
c = read_eeprom(addr);
P2=c;
}
}