#include "i2c.h"    //包含i2c.h头文件，注意自建的头文件是用双引号
void c02_delay()   //微秒级延时函数
{ ;; }

void start()  //起始信号
{	
	sda=1;
	c02_delay();
	scl=1;
	c02_delay();
	sda=0;
	c02_delay();
}

void stop()   //终止信号
{
	sda=0;
	c02_delay();
	scl=1;
	c02_delay();
	sda=1;
	c02_delay();
}

void respons()   //应答信号
{
	uchar i;
	scl=1;
	c02_delay();
    while((sda==1)&&(i<250))i++;    //如sda=0或i>250,,跳出 
	scl=0;
	c02_delay();
}

void c_init()	//I2C初始化
{
	sda=1;
	c02_delay();
	scl=1;
	c02_delay();
}

void c02_write_byte(uchar date)  //写入一个字节到I2C总线
{
	uchar i,temp;
	temp=date;
	for(i=0;i<8;i++)
	{
		temp=temp<<1;
		scl=0;
	    c02_delay();
		sda=CY;
		c02_delay();
		scl=1;
		c02_delay();
	}
	scl=0;
	c02_delay();
	sda=1;
	c02_delay();
}

uchar c02_read_byte()   //从I2C读一个字节
{
	uchar i,k;
	scl=0;
	c02_delay();
	sda=1;
	c02_delay();
	for(i=0;i<8;i++)
	{
		scl=1;
		c02_delay();	
		k=(k<<1)|sda;
		scl=0;
		c02_delay();	
	}
	return k;
}

void c02_write_add(uchar address,uchar date)	//at24c02按字节写入函数
{
	start();
	c02_write_byte(0xa0);
	respons();
	c02_write_byte(address);
	respons();
	c02_write_byte(date);
	respons();
	stop();
}

uchar c02_read_add(uchar address)		//对at24c02随机读函数
{
	uchar date;
	start();
	c02_write_byte(0xa0);
	respons();
	c02_write_byte(address);
	respons();
	start();
	c02_write_byte(0xa1);
	respons();
	date=c02_read_byte();
	stop();
	return date;
}