#include
#define uchar unsigned char //界说一下方便使用
#define uint unsigned int
#define ulong unsigned long
#define WriteDeviceAddress 0xa0 //界说器材在IIC总线中的地址
#define ReadDviceAddress 0xa1
sbit SCL=P2^7;
sbit SDA=P2^6;
sbit P20=P2^0;
//守时函数
void DelayMs(unsigned int number)
{
unsigned char temp;
for(;number!=0;number–)
{
for(temp=112;temp!=0;temp–) ;
}
}
//开端总线
void Start()
{
SDA=1;
SCL=1;
SDA=0;
SCL=0;
}
//完毕总线
void Stop()
{
SCL=0;
SDA=0;
SCL=1;
SDA=1;
}
//发ACK0
void NoAck()
{
SDA=1;
SCL=1;
SCL=0;
}
//测验ACK
bit TestAck()
{
bit ErrorBit;
SDA=1;
SCL=1;
ErrorBit=SDA;
SCL=0;
return(ErrorBit);
}
//写入8个bit到24c02
Write8Bit(unsigned char input)
{
unsigned char temp;
for(temp=8;temp!=0;temp–)
{
SDA=(bit)(input&0x80);
SCL=1;
SCL=0;
input=input<<1;
}
}
//写入一个字节到24c02中
void Write24c64(uchar ch,uchar address)
{
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Write8Bit(ch);
TestAck();
Stop();
DelayMs(10);
}
//从24c02中读出8个bit
uchar Read8Bit()
{
unsigned char temp,rbyte=0;
for(temp=8;temp!=0;temp–)
{
SCL=1;
rbyte=rbyte<<1;
rbyte=rbyte|((unsigned char)(SDA));
SCL=0;
}
return(rbyte);
}
//从24c02中读出1个字节
uchar Read24c64(uchar address)
{
uchar ch;
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Start();
Write8Bit(ReadDviceAddress);
TestAck();
ch=Read8Bit();
NoAck();
Stop();
return(ch);
}
//本课实验写入一个字节到24c02并读出来验证
void main(void) // 主程序
{
uchar c1;
uchar address =
for ( address =
{
Write24c64(0x00,address);// 将0x88写入到24c02的第2个地址空间
c1=Read24c64(address);
}
P20=0;
while(1); //程序挂起
}