I2C總線相關(guān)函數(shù):本文引用地址:http://www.ex-cimer.com/article/201611/318122.htmvoid I2Cstart()//開始標(biāo)志{ SDA=1;SCL=1;SDA=0;delay1ms(4);SCL=0;delay1ms(4);}void I2Cstop()//結(jié)束標(biāo)志{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寫數(shù)據(jù)的過(guò)程{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;//給足夠時(shí)間讓數(shù)據(jù)讀取delay1ms(4);}SCL=0;SDA=1; //因?yàn)?strong>總線上有一個(gè)信號(hào)為低則低delay1ms(4);SCL=1;delay1ms(4);//等待應(yīng)答位SCL=0;}unsigned char I2Cread(void){unsigned char i,byte;byte =0;for(i=0;i<8;i++){SCL=0;SDA=1;//讀數(shù)據(jù)必須拉高delay1ms(4);SCL=1;//數(shù)據(jù)穩(wěn)定delay1ms(4);byte<<=1;if(SDA==1){byte|=0x01;}delay1ms(4);}SCL=0;delay1ms(4);SDA=0;//發(fā)送的應(yīng)答位delay1ms(4);SCL=1;delay1ms(4);SCL=0;return byte;}unsigned char I2Cread_eeprom(unsigned char addr)//I2C讀取數(shù)據(jù){unsigned char datebyte,datebyte2;I2Cstart();I2Csend(0xa0);//寫數(shù)據(jù)I2Csend(addr);I2Cstart();I2Csend(0xa1);//讀數(shù)據(jù)datebyte2=I2Creadack();datebyte=I2Cread();I2Cstop();return datebyte;}void write_eeprom(unsigned char addr,unsigned char datebyte){I2Cstart();I2Csend(0xa0);I2Csend(addr);I2Csend(datebyte);I2Cstop();}
評(píng)論