51单片机I2C总线代码

I2C总线相关函数:

void I2Cstart()//开始标志
{	
	SDA=1;
	SCL=1;
	SDA=0;
	delay1ms(4);
	SCL=0;
	delay1ms(4);
}
void I2Cstop()//结束标志
{
	SCL=0;
	delay1ms(4);
	SDA=0;
	delay1ms(4);
	SCL=1;
	delay1ms(4);
	SDA=1;
	delay1ms(4);
}
unsigned char I2Creadack()
{
	unsigned char i,byte;
	byte=0;
	for(i=0;i<8;i++)
	{
		SCL=0;
		SDA=1;
		delay1ms(4);
		byte<<=1;
		if(SDA==1)
		{
			byte|=0x01;
			delay1ms(4);
		}
	}
	SCL=0;
	delay1ms(4);
	SDA=0;
	delay1ms(4);
	SCL=1;
	delay1ms(4);
	SCL=0;
	return byte;
}
void I2Csend(unsigned char byte)//I2C写数据的过程
{

	unsigned char mask,i;
	for(i=0;i<8;i++)
	{	
		SCL=0;
		if((mask&byte)==0)
		{
			SDA=0;
		}
		else
		{
			SDA=1;
		}
		mask>>=1;
		delay1ms(4);
		SCL=1;//给足够时间让数据读取
		delay1ms(4);

	}
	SCL=0;
	SDA=1;		//因为总线上有一个信号为低则低
	delay1ms(4);
	SCL=1;
	delay1ms(4);//等待应答位
	SCL=0;
}
unsigned char I2Cread(void)
{
	unsigned char i,byte;
	byte =0;
	for(i=0;i<8;i++)
	{
		SCL=0;
		SDA=1;//读数据必须拉高
		delay1ms(4);
		SCL=1;//数据稳定
		delay1ms(4);
		byte<<=1;
		if(SDA==1)
		{
			byte|=0x01;
		}
		delay1ms(4);
	}
	SCL=0;
	delay1ms(4);
	SDA=0;//发送的应答位
	delay1ms(4);
	SCL=1;
	delay1ms(4);
	SCL=0;
	return byte;
}
unsigned char I2Cread_eeprom(unsigned char addr)//I2C读取数据
{
	unsigned char datebyte,datebyte2;
	I2Cstart();
	I2Csend(0xa0);//写数据
	I2Csend(addr);
	I2Cstart();
	I2Csend(0xa1);//读数据
	datebyte2=I2Creadack();
	datebyte=I2Cread();
	I2Cstop();
	return datebyte;

}

void write_eeprom(unsigned char addr,unsigned char datebyte)
{
	I2Cstart();
	I2Csend(0xa0);
	I2Csend(addr);
	I2Csend(datebyte);
	I2Cstop();
}


你可能感兴趣的:(实验练习)