C51入门3,IIC通信实验
扫描二维码
随时随地手机看文章
实验一:写入按键次数在24C04上,并读出显示在4个LED上。
程序:
//写入按键次数在24C04上,并读出显示在4个LED上
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
#include
//定义器件在IIC总线的地址和端口设置
#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;
//定时函数
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;
}
//结束总线
void stop()
{SDA=0;
SCL=0;
SDA=1;
SCL=1;
}
//发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;
}
}
//写入一个字节到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读出一个字节
uchar Read24c02(uchar address)
{
uchar ch;
Start();
Write8Bit(WriteDeviceAddress);
TestAck();
Write8Bit(address);
TestAck();
Start();
Write8Bit(ReadDeviceAddress);
TestAck();
ch=Read8Bit();
NoAck();
stop();
return(ch);
}
//写入按键次数到24C02上,并显示在LED上
//主函数
void main(void)
{
uchar c1,c2;
while(1)
{
c1=Read24c02(0x01);//读出24C02第一地址数据
P1=c1;//显示在P1的4个LED上
if (!K1)//按键处理
{
c1++;//值加一
Write24c02(c1,0x01);//重新写入
while(!K1);//按键松开
for (c2=0;c2<250;c2++);//消抖动
}
}
}