#include "i2c.h"  //包含i2c.h头文件，注意自建的头文件是用双引号
void delay()   //微秒级延时函数
{
	;;  //用两个空语句实现短时间延时，当晶振为11.0592MHz时，约4~5微秒
}
void start()  //起始信号
{
	SDA=1;
	SCL=1;
	delay();
	SDA=0;
	delay();
}

void stop()  //终止信号
{
	SDA=0;
	SCL=1;
	delay();
	SDA=1;
	delay();
}

void ack()  //应答信号
{
	uchar i;
	SCL=1;
	delay();
	while((SDA==1)&&(i<250))i++;
	SCL=0;
	delay();
}

void nack()  //无应答信号
{
	SCL=1;
	delay();
	SDA=1;
	SCL=0;
	delay();
}

void write_byte(uchar date) //写入一个字节到I2C总线
{
	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();
	SDA=1;
	delay();
}

uchar read_byte() //从I2C读一个字节
{
	uchar i,j,k;
	SCL=0;
	delay();
	for(i=0;i<8;i++)
	{
		SCL=1;
		delay();
		j=SDA;
		k=(k<<1)|j;
		SCL=0;
		delay();
	}
	return k;
}

void write_at24c02(uchar address ,uchar date)  //at24c02按字节写入函数
{
	start();
	write_byte(0xa0);
	ack();
	write_byte(address);
	ack();
	write_byte(date);
	ack();
	stop();
}

uchar read_at24c02(uchar address)  //对at24c02随机读函数
{
	uchar date;
	start();
	write_byte(0xa0);
	ack();
	write_byte(address);
	ack();
	start();
	write_byte(0xa1);
	ack();
	date=read_byte();
	nack();
	stop();
	return date;
}
