#include
#include//我的自界说LCD1602头文件
/*—————————————————————
24C32可存储4K(1024*4)个字节(8bit),因而寻址地址最大为0x0FFF,24C32为从机。
—————————————————————-*/
#defineWriteDeviceAddress0x0A2//界说器材在I2C总线中的写地址(留意:依据自界说从机地址接口改动)
#defineReadDviceAddress0x0A3//界说器材在I2C总线中的读地址(留意:依据自界说从机地址接口改动)
sbitSCL=P0^4;//我的24C32接口设置
sbitSDA=P3^7;
//2us延时子程序
voiddelay_2us(uchari)
{
while(–i);
}
//开端总线
voidStart()
{
SDA=1;
SCL=1;
delay_2us(1);
SDA=0;
delay_2us(1);
SCL=0;
}
//完毕总线
voidStop()
{
SDA=0;
SCL=1;
delay_2us(1);
SDA=1;
delay_2us(1);
SDA=0;
SCL=0;
}
//发送应对位信号
//voidMACK()
//{
//SDA=0;
//SCL=1;
//delay_2us(1);
//SCL=0;
//SDA=1;
//}
//发送非应对位信号
voidMNACK()
{
SDA=1;
SCL=1;
delay_2us(1);
SCL=0;
SDA=0;
}
//检测从机应对信号
bitCACK()
{
bitflag;
SDA=1;
SCL=1;
delay_2us(1);
flag=SDA;
SCL=0;
return(flag);
}
/*————————————————————————–
//写入8个bit到24C32
—————————————————————————*/
Write8Bit(ucharinput)
{
uchartemp;
for(temp=0;temp《8;temp++)
{
SDA=(bit)(input&0x80);
SCL=1;
delay_2us(1);
SCL=0;
input=input《《1;
}
}
/*————————————————————————–
//写入一个字节到24C32中
—————————————————————————*/
voidWrite24C32(ucharch,uintaddress)
{
Start();
Write8Bit(WriteDeviceAddress);
while(CACK());
Write8Bit(address/256);(留意:地址分两次传送,高位在前!)
while(CACK());
Write8Bit(address%256);
while(CACK());
Write8Bit(ch);
while(CACK());
Stop();
}
/*————————————————————————–
//从24C32中读出8个bit
—————————————————————————*/
ucharRead8Bit()
{
unsignedchartemp,rbyte=0;
for(temp=0;temp《8;temp++)
{
SDA=1;
SCL=1;
rbyte=rbyte|((unsignedchar)(SDA));
if(temp《7)//留意:仅左移7次
{
rbyte=rbyte《《1;
}
SCL=0;
}
return(rbyte);
}
/*————————————————————————–
从24c32中读出1个字节
—————————————————————————*/
ucharRead24C32(uintaddress)
{
ucharch;
Start();
Write8Bit(WriteDeviceAddress);
while(CACK());
Write8Bit(address/256);
while(CACK());
Write8Bit(address%256);
while(CACK());
Start();
Write8Bit(ReadDviceAddress);
while(CACK());
ch=Read8Bit();
MNACK();
Stop();
return(ch);
}
/*————————————————————————–
主函数
—————————————————————————*/
voidmain(void)//主程序
{
ucharnewchar;
LCD1602_init();//1602初始化
Write24C32(‘8’,0x01FF);//写‘5’进0x1FF
LCD1602_puts(0,0,“24C32W_TestOK!”);
newchar=Read24C32(0x01FF);//从0x1FF接纳数据
LCD1602_puts(0,1,“ReadValue=”);
LCD1602_puts(10,1,newchar);
while(1);
}