微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 51单片机I2C总线代码

51单片机I2C总线代码

时间:11-19 来源:互联网 点击:
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();}

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top