用I2C通信实现点亮一盏小灯(包含应答)---c语言

//详细报告请下载:http://download.csdn.net/detail/chenqiai0/4482112
 
/*用I2C通信实现点亮一盏小灯*/
#include
#define uchar unsigned char
sbit scl = P3^7;
sbit sda = P3^6;

sbit ADDR0=P1^0;
sbit ADDR1=P1^1;
sbit ADDR2=P1^2;
sbit ENLED1=P1^4;
sbit ENLED2=P1^3;
uchar a;
void delay()
{ ;; }
void start()  //开始信号
{	
	sda=1;
	delay();
	scl=1;
	delay();
	sda=0;
	delay();
}

void stop()   //停止
{
	sda=0;
	delay();
	scl=1;
	delay();
	sda=1;
	delay();
}

void respons()  //应答
{
	uchar i;
	scl=1;
	delay();
	while((sda==1)&&(i<250))i++;        //收到应答SDA=0 或超过时间就不等待了
	scl=0;
	delay();
}

void init()
{
	sda=1;
	delay();
	scl=1;
	delay();
}

void write_byte(uchar date)
{
	uchar i,temp;
	temp=date;


	for(i=0;i<8;i++)
	{
		temp=temp<<1;
		scl=0;
	    delay();
		sda=CY;
		delay();
		scl=1;
		delay();
	//	scl=0;
     //   delay();
	}
	scl=0;
	delay();
	sda=1;
	delay();
}

uchar read_byte()
{
	uchar i,k;
	scl=0;
	delay();
	sda=1;
	delay();
	for(i=0;i<8;i++)
	{
		scl=1;
		delay();	
		k=(k<<1)|sda;
		scl=0;
		delay();	
	}
	return k;
}

void delay1(uchar x)
{
	uchar a,b;
	for(a=x;a>0;a--)
	 for(b=100;b>0;b--);
}

void write_add(uchar address,uchar date)
{
	start();
	write_byte(0xa0);
	respons();
	write_byte(address);
	respons();
	write_byte(date);
	respons();
	stop();
}

uchar read_add(uchar address)
{
	uchar date;
	start();
	write_byte(0xa0);
	respons();
	write_byte(address);
	respons();
	start();
	write_byte(0xa1);
	respons();
	date=read_byte();
	stop();
	return date;
}

void main()
{	ENLED1=0;
    ENLED2=1;
	ADDR0=0;
	ADDR1=1;
	ADDR2=1;
	init();
	write_add(23,0x01);
	delay1(100);
	P0=read_add(23);
	P0=~P0;
	while(1);
}

有问题希望大家可以留言,谢谢

你可能感兴趣的:(51单片机)