说明:该程序今本人调试成功,在这是用数码管显示单片机中储存的数据。可以应用到用PC主机控制其它设备的系统中。
#include
#define uchar unsigned char
sbit SCL="P2"^0;
sbit SDA="P2"^1;
sbit P36=P3^6;
sbit P37=P3^7;
uchar code send[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8};
uchar show[8];
bit back;
//延时-------------------------------------------
void delay()
{ uchar i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++);
}
void delay_lms()
{ uchar i,j,k;
for(i=0;i<200;i++)
for(j=0;j<200;j++)
for(k=0;k<4;k++);
}
//启动程序------------------------------------------
void start()
{
SDA="1";
SCL="1";
delay();
SDA="0";
delay();
SCL="0";
}
//停止程序--------------------------------------------
void stop()
{
SDA="0";
delay();
SCL="1";
delay();
SDA="1";
delay();
SCL="0";
}
//应答检查程序----------------------------------------------
void check()
{
SDA="1";
delay();
SCL="1";
delay();
back="SDA";
SCL="0";
SDA="0";
}
//-----------------------------------------------------------------------
void nocheck()
{
SDA="1" ;
delay();
SCL="1" ;
delay();
SCL="0";
}
//I2C写一个字节程序----------------------------------------------------
void write8tybe(uchar temp)
{
uchar k="8";
while(k--)
{
if((temp&0x80)==0x80) //发送最高位为1
{
SDA="1";
delay();
SCL="1";
delay();
SCL="0";
}
else
{
SDA="0";
delay();
SCL=1;
delay();
SCL=0;
}
temp="temp"<<1; //左移动
}
}
//单字节写入--------------------------------------------------------------------------
void write_tybe(uchar ramadd,uchar romadd,uchar *s,uchar n)
{
uchar m;
do{
do{
do{
start();
write8tybe(ramadd); //控制字
check();
}
while(back);
delay();
write8tybe(romadd); //字节地址
check();
}
while(back);
delay();
for(m=0;m
check();
if(back) break;
delay();}
}
while(back);
stop();
P36=0;
}
//I2C读一个字节程序-------------------------------------------------------------
uchar read8tybe()
{
bit q;
uchar b="0";
uchar i;
SDA=1;
for(i=8;i>0;i--)
{
SCL="1";
delay();
q="SDA";
SCL="0";
delay();
if(q==1) { b="b"<<1; b="b|0x01";} //数据的最后一位置1
else b="b"<<1;
}
return (b);
}
//读单字节程序----------------------------------------------------------------
void read_tybe(uchar ramadd,uchar romadd,uchar n)
{ uchar x,save;
do{
do{
do{start();
write8tybe(ramadd);
check();}
while(back);
delay();
write8tybe(romadd);
check();}
while(back);
delay();
start();
write8tybe(0xa1);
check();}
while(back);
delay();
for(x=0;x
save="read8tybe"();
SDA="0";
delay();
SCL="1";
delay(); //主机接收一个字节后,主机给从机回送个低电平(有效)脉冲
SCL="0";
show[x]=save;
delay();
}
nocheck();
stop();
P37=0;
}
//---------------------------------------------------------------------------
void main(void)
{
uchar w;
P36=1;
P37=1;
P2=0x7f;
write_tybe(0xa0,0x20,send,8);
delay();
read_tybe(0xa0,0x20,8);
for(w=0;w<8;)
{
P0=show[w++];
if(w==8) w="0";
delay_lms();
}
}