實驗一:寫入按鍵次數(shù)在24C04上,并讀出顯示在4個LED上。
程序:
//寫入按鍵次數(shù)在24C04上,并讀出顯示在4個LED上
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
#include
//定義器件在IIC總線的地址和端口設(shè)置
#define WriteDeviceAddress 0xa0
#define ReadDeviceAddress 0xa1
sbit SCL=P2^1;
sbit SDA=P2^0;
sbit P10=P1^0;
sbit K1=P3^2;
char code dx516[3] _at_ 0x003b;
//定時函數(shù)
void DelayMs(uint number)
{
uchar temp;
for (;number!=0;number--)
{for (temp=112;temp!=0;temp--);
}
}
//開始總線
void Start()
{
SDA=1;
SCL=1;
SDA=0;
SCL=0;
}
//結(jié)束總線
void stop()
{SDA=0;
SCL=0;
SDA=1;
SCL=1;
}
//發(fā)ACK0
void NoAck()
{
SDA=1;
SCL=1;
SCL=0;
}
//測試ACK0
bit TestAck()
{
bit ErrorBit;
SDA=1;
SCL=1;
ErrorBit=SDA;
SCL=0;
return(ErrorBit);
}
//寫入8個bit到24C04
Write8Bit(uchar input)
{
uchar temp;
for (temp=8;temp!=0;temp--)
{
SDA=(bit)(input&0x80);
SCL=1;
SCL=0;
input=input<<1;
}
}
//寫入一個字節(jié)到24C04
void Write24c02(uchar ch,uchar address)
{
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Write8Bit(ch);
TestAck();
stop();
DelayMs(10);
}
//從24C04讀出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);
}
//從24C04讀出一個字節(jié)
uchar Read24c02(uchar address)
{
uchar ch;
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Start();
Write8Bit(ReadDeviceAddress);
TestAck();
ch=Read8Bit();
NoAck();
stop();
return(ch);
}
//寫入按鍵次數(shù)到24C02上,并顯示在LED上
//主函數(shù)
void main(void)
{
uchar c1,c2;
while(1)
{
c1=Read24c02(0x01);//讀出24C02第一地址數(shù)據(jù)
P1=c1;//顯示在P1的4個LED上
if (!K1)//按鍵處理
{
c1++;//值加一
Write24c02(c1,0x01);//重新寫入
while(!K1);//按鍵松開
for (c2=0;c2<250;c2++);//消抖動
}
}
}