#define YANSHI 60 void delay (uint32 i) { while(--i); }
void Start_I2c() { IO0DIR=(IO0DIR&0xfffffff7)|0x00000008;//SDA输出 IO0SET=(IO0PIN&0xfffffff7)|0x00000008; //SDA置1 delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004; //SCL置1 delay(YANSHI); IO0CLR=(IO0PIN&0xfffffff7)|0x00000008; //SDA置0 delay(YANSHI); IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; //SCL置0 delay(YANSHI); } void Stop_I2c() { IO0DIR=(IO0DIR&0xfffffff7)|0x00000008;//SDA输出 IO0CLR=(IO0PIN&0xfffffff7)|0x00000008;//SDA置0 delay(YANSHI); IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004;//SCL置1 delay(YANSHI); IO0SET=(IO0PIN&0xfffffff7)|0x00000008;//SDA置1 delay(YANSHI); } /*********************************** 字节数据传送函数 函数原理:void SendByte(uchar c); 功能:将数据c发送出去,可以是地址,也可以是数据,发完后等待应答,并对此状态位进行操作(不应答或非应答都使ack=0 假)。 发送数据正常,ack=1;ack=0表示被控器无应答或损坏。 ****************************************/ void SendByte(uint8 c) { uint8 BitCnt; IO0DIR=(IO0DIR&0xfffffff7)|0x00000008; //SDA输出 for(BitCnt=0;BitCnt<8;BitCnt++) { if((c&0x80)==0x80) IO0SET=(IO0PIN&0xfffffff7)|0x00000008;//SDA置1 else IO0CLR=(IO0PIN&0xfffffff7)|0x00000008;//SDA置0 delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004; //SCL置1 delay(YANSHI); IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; //SCL置0 c=c<<1; } delay(YANSHI); IO0SET=(IO0PIN&0xfffffff7)|0x00000008; //SDA置1 delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004; //SCL置1 delay(YANSHI); IO0DIR=(IO0DIR&0xfffffff7); //SDA输入 delay(YANSHI); sda_value=IO0PIN; if((IO0PIN&0x00000008)==0x00000008) ack=0; else ack=1; IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; //SCL置0 delay(YANSHI); } /***************************************** 字节数据传送函数 函数原形:uchar RcvByte(); 功能:用来接收从器件传来的数据,并判断总线错误(不发应答信号), 发完后请用应答函数。 *******************************************/ uint8 RcvByte() { uint8 retc; uint8 BitCnt; retc=0; IO0DIR=(IO0DIR&0xfffffff7)|0x00000008; //SDA输出 IO0SET=(IO0PIN&0xfffffff7)|0x00000008; //SDA置1 IO0DIR=(IO0DIR&0xfffffff7);//SDA输入 for(BitCnt=0;BitCnt<8;BitCnt++) { delay(YANSHI); IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; //SCL置0 delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004; //SCL置1 delay(YANSHI); retc=retc<<1; if((IO0PIN&0x00000008)==0x00000008) retc=retc+1; delay(YANSHI); } IO0CLR=(IO0PIN&0xfffffffb)|0x00000004; //SCL置0 delay(YANSHI); return(retc); } /******************************************* 应答子函数 原形:viod Ack_I2c(bit a); 功能:主控器进行应答信号,(可以是应答或非应答信号) **********************************************/ void Ack_I2c(uint8 a) { IO0DIR=(IO0DIR&0xfffffff7)|0x00000008;//SDA输出 if(a==1) IO0SET=(IO0PIN&0xfffffff7)|0x00000008;//SDA置1 else IO0CLR=(IO0PIN&0xfffffff7)|0x00000008;//SDA置0 delay(YANSHI); IO0SET=(IO0PIN&0xfffffffb)|0x00000004;//SCL置1 delay(YANSHI); IO0CLR=(IO0PIN&0xfffffffb)|0x00000004;//SCL置0 delay(YANSHI); }
|