24c64讀寫程序
#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;
//定時函數(shù)
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;
}
//結(jié)束總線
void Stop()
{
SCL=0;
SDA=0;
SCL=1;
SDA=1;
}
//發(fā)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;
}
}
//寫入一個字節(jié)到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個字節(jié)
uchar Read24c64(uchar address)
{
uchar ch;
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Start();
Write8Bit(ReadDviceAddress);
TestAck();
ch=Read8Bit();
NoAck();
Stop();
return(ch);
}
//本課試驗寫入一個字節(jié)到24c02并讀出來驗證
void main(void) // 主程序
{
uchar c1;
uchar address =
for ( address =
{
Write24c64(0x00,address);// 將0x88寫入到24c02的第2個地址空間
c1=Read24c64(address);
}
P20=0;
while(1); //程序掛起
}
評論