#include <reg52.h>
sbit scl=P1^2;
sbit sda=P1^1;
sbit led1=P3^7;
sbit led2=P3^6;
sbit led3=P3^5;
sbit led4=P3^4;
void yanshi()
{
;;
}
void iic_init()//总线初始化,降总线拉高以释放总线
{
scl=1;
yanshi();
sda=1;
yanshi();
}
void iic_start()//启动信号,在SCL高电平期间,SDA一个下降沿启动信号
{
scl=1;
yanshi();
sda=1;
yanshi();
sda=0;
yanshi();
}
void respons()//应答信号,SCL高电平期间,SDA被从设备拉低表示应答
{
unsigned char a;
scl=1;
yanshi();
while((sda==1)&&(a<250))a++;
scl=0;
yanshi();
}
void stop()//SCL在高电平期间,SDA一个上升沿信号表示停止
{
sda=0;
yanshi();
scl=1;
yanshi();
sda=1;
yanshi();
}
void write_byte(unsigned char date)//写一个字节
{
unsigned char i,temp;
temp=date;
for(i=0;i<8;i++)
{
temp=temp<<1;
scl=0;
yanshi();
sda=CY;
yanshi();
scl=1;
yanshi();
}
scl=0;
yanshi();
sda=1;
yanshi();
}
unsigned char read_byte()//读一个字节
{
unsigned char i,k;
scl=0;
yanshi();
sda=1;
yanshi();
for(i=0;i<8;i++)
{
scl=1;
yanshi();
k=(k<<1)|sda;
scl=0;
yanshi();
}
return k;
}
void write_add(unsigned char address,unsigned char date)//写片内地址,数据
{
iic_start();
write_byte(0xa0);//写片选地址
respons();
write_byte(address);//写片内地址
respons();
write_byte(date);//写数据
respons();
stop();
}
void nack()
{
scl=1;
yanshi();
sda=1;
scl=0;
yanshi();
}
unsigned read_add(unsigned char address)//读片内地址,数据
{
unsigned char date;
iic_start();
write_byte(0xa0);//写片选地址
respons();
write_byte(address);//写片内地址
respons();
iic_start();//开始信号
write_byte(0xa1);//读命令
respons();
date=read_byte();//读片内数据,把数据赋值给date
nack();
stop();
return date;
}
void yanshi_10ms()
{
unsigned char a,b;
for(a=50;a>0;a--)
{
for(b=200;b>0;b--);
}
}
void main()
{
unsigned int aaa;
iic_init();
iic_start();
led1=0;
write_add(10,0xf0);
led2=0;
yanshi_10ms();
led3=0;
aaa=read_add(10);
led4=0;
while(1);
}
-
一周热门 更多>