i2c 24c02简单的应用
#include<reg52.h>
#define uchar unsigned char
sbit ledlk=P1^0;
sbit smglk=P1^1;
sbit scl=P1^4;
sbit sda=P1^3;
void delay()
{;;}
void delayms(uchar ms)
{
uchar i,j;
for(i=ms;i>0;i--)
for(j=100;j>0;j--);
}
void init()
{
smglk=0;
}
void start()
{
sda=1;
delay();
scl=1;
sda=0;
delay();
}
void stop()
{
sda=0;
delay();
scl=1;
delay();
delay();
sda=1;
delay();
delay();
}
void answ()
{
uchar i;
scl=1;
while((sda==1)&&(i<4))i++;
scl=0;
}
void write_byte(uchar tmp)
{
uchar i;
for(i=0;i<8;i++)
{
tmp=tmp<<1;
scl=0;
sda=CY;
scl=1;
}
scl=0;
}
uchar read_byte()
{
uchar i,k;
scl=0;
for(i=0;i<8;i++)
{
scl=1;
k=(k<<1)|sda;
scl=0;
}
return k;
}
void write(uchar add,uchar date)
{
start();
write_byte(0xa0);
answ();
write_byte(add);
answ();
write_byte(date);
answ();
stop();
}
uchar read(uchar add)
{
uchar tmp;
start();
write_byte(0xa0);
answ();
write_byte(add);
answ();
start();
write_byte(0xa1);
answ();
tmp=read_byte();
stop();
return tmp;
}
void main()
{
unsigned int i;
init();
for(i=0;i<256;i++)
{
write(23,i);
delayms(1000);
P2=read(23);
}
while(1);
}
#define uchar unsigned char
sbit ledlk=P1^0;
sbit smglk=P1^1;
sbit scl=P1^4;
sbit sda=P1^3;
void delay()
{;;}
void delayms(uchar ms)
{
uchar i,j;
for(i=ms;i>0;i--)
for(j=100;j>0;j--);
}
void init()
{
smglk=0;
}
void start()
{
sda=1;
delay();
scl=1;
sda=0;
delay();
}
void stop()
{
sda=0;
delay();
scl=1;
delay();
delay();
sda=1;
delay();
delay();
}
void answ()
{
uchar i;
scl=1;
while((sda==1)&&(i<4))i++;
scl=0;
}
void write_byte(uchar tmp)
{
uchar i;
for(i=0;i<8;i++)
{
tmp=tmp<<1;
scl=0;
sda=CY;
scl=1;
}
scl=0;
}
uchar read_byte()
{
uchar i,k;
scl=0;
for(i=0;i<8;i++)
{
scl=1;
k=(k<<1)|sda;
scl=0;
}
return k;
}
void write(uchar add,uchar date)
{
start();
write_byte(0xa0);
answ();
write_byte(add);
answ();
write_byte(date);
answ();
stop();
}
uchar read(uchar add)
{
uchar tmp;
start();
write_byte(0xa0);
answ();
write_byte(add);
answ();
start();
write_byte(0xa1);
answ();
tmp=read_byte();
stop();
return tmp;
}
void main()
{
unsigned int i;
init();
for(i=0;i<256;i++)
{
write(23,i);
delayms(1000);
P2=read(23);
}
while(1);
}