#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit SCL=P2^1;
sbit SDA=P2^0;
#define SCL_SET SCL=1
#define SCL_CLR SCL=0
#define SDA_SET SDA=1
#define SDA_CLR SDA=0
void Delay(uint cnt)
{
while(--cnt);
}
void start()
{
SDA_SET;
Delay(1);
SCL_SET;
Delay(5);
SDA_CLR;
}
void stop()
{
SDA_CLR;
Delay(1);
SCL_SET;
Delay(5);
SDA_SET;
}
void ack()
{
SDA_CLR;
SCL_SET;
Delay(1);
SCL_CLR;
}
void noAck()
{
SDA_SET;
SCL_SET;
Delay(1);
SCL_CLR;
}
void send(uchar Data)
{
uchar i=0;
uchar temp=0;
temp=Data;
for(i=0; i<8; i++)
{
SCL_CLR;
Delay(1);
if(temp&0x80) SDA_SET;
else SDA_CLR;
Delay(1);
SCL_SET;
Delay(1);
temp<<=1;
}
SCL_CLR;
}
uchar recive()
{
uchar i=0;
uchar temp=0;
SDA_SET;
for(i=0; i<8; i++)
{
SCL_CLR;
Delay(1);
SCL_SET;
Delay(2);
if(SDA) temp|=0x01;
else temp&=0xfe;
if(i<7) temp<<=1;
}
SCL_CLR;
return temp;
}
void main()
{
start();
send(0xa0);
ack();
send(23);
ack();
send(0xfe);
ack();
stop();
Delay(100);
start();
send(0xa0);
ack();
send(23);
ack();
start();
send(0xa1);
ack();
P1=recive();
noAck();
stop();
while(1);
}
-------------------------------------------------------------------
我学了好几天I2C总线操作了,看了不少例程,感觉不同人都有不一样的写法,可是自己动手时总是会出问题。好不容易搞出来了,感觉像是碰巧写对的,因为换种方法又不行了,希望前辈们不吝指教!
|