#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);
}