#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);
}
評論
查看更多