單片機模擬I2C總線讀寫EEPROM(24CXX)程序二
電路不變,下面是仿真電路,只不過P2口的數(shù)碼管由觀測程序執(zhí)行到哪一步改為查看接收緩沖區(qū)的數(shù)據(jù)。
本文引用地址:http://www.ex-cimer.com/article/201611/316792.htm程序如下:
#include
#define unit unsigned int
#define uchar unsigned char
uchar num=4;
uchar idata sendbuf[4]={0x96,0x84,0xd5,0x63};
uchar idata recivebuf[4];
sbit scl=P0^0;
sbit sda=P0^1;
sbit led0=P2^0;
sbit led1=P2^1;
sbit led2=P2^2;
sbit led3=P2^3;
sbit led4=P2^4;
sbit led5=P2^5;
sbit led6=P2^6;
sbit led7=P2^7;
delay(void) //delay
{
int i;
for(i=0;i<1;i++);
}
start(void) //start
{
sda=1;
scl=1;
delay();
sda=0;
delay();
scl=0;
}
stop(void) //stop
{
sda=0;
scl=1;
delay();
sda=1;
delay();
scl=0;
}
answer(void) //answer
{
sda=1;
scl=1;
delay();
sda=0;
scl=0;
}
noanswer(void)//no answer
{
sda=1;
scl=1;
delay();
sda=1;
scl=0;
}
checkanswer(void) //check answer
{
sda=1;
scl=1;
F0=0;
if(sda==1) F0=1;
scl=0;
}
sendabyte(uchar idata *saddress) //send a byte
{
uchar n=8,temp=*saddress;
while(n--)
{
if((temp&0x80)==0x80) sda=1;
else sda=0;
delay();
scl=1;
delay();
scl=0;
temp=temp<<1;
}
checkanswer();
if(F0==1) return;
}
reciveabyte(uchar idata *raddress) //recive a byte
{
uchar n=8,temp;
while(n--)
{
scl=1;
temp=temp<<1;
if(sda==1)
temp=temp|0x01;
else
temp=temp&0xfe;
scl=0;
}
*raddress=temp;
}
sendnbyte(uchar n) //send n byte
{
uchar idata *ps;
ps=&sendbuf[0];
while(n--)
{
sendabyte(ps);
ps++;
}
stop();
}
recivenbyte(uchar n) //recive n byte
{
uchar idata *pr;
pr=&recivebuf[0];
while(n--)
{
reciveabyte(pr);
answer();
pr++;
}
noanswer();
stop();
}
main(void) //MAIN
{
start();
sendabyte(0xa0);
sendabyte(0x00);
sendnbyte(num);
/*-----------------------*/
start();
sendabyte(0xa1);
recivenbyte(num);
P2=recivebuf[7];
}
程序說明:
程序開始的num定義了傳送數(shù)據(jù)的個數(shù),以及發(fā)送緩沖區(qū)和接收緩沖區(qū)。
主函數(shù)的操作一目了然,不多介紹。
存在的問題:這段程序中我定義了接收緩沖區(qū)的數(shù)據(jù)是4個,也的確接收到了4個數(shù)據(jù)。但接收到的數(shù)據(jù)確是從recivebuf[4]開始的,像本例中,recivebuf[4]中存放0X96,recivebuf[5]中存放0X84,recivebuf[6]中存放0XD5,recivebuf[7]中存放0X63。
評論