/************从SD2200发送一个字节*************/ void I2CSendByte(uchar demand,bit order) //order=1,H_L;order=0,L_H { uchar i=8; //order=1,从HI-->LO发送8bit数据 //order=0,从LO-->HI发送8bit数据 if(order) { while(i--) { SCL=0; _nop_(); SDA=(bit)(demand&0x80); demand<<=1; I2CWait(); SCL=1; I2CWait(); } SCL=0; } else { while(i--) { SCL=0; _nop_(); SDA=(bit)(demand&0x01); demand>>=1; I2CWait(); SCL=1; I2CWait(); } SCL=0; } }
/*********发送 ACK*********/ void I2CAck(void) { SDA=0; SCL=0; I2CWait(); SCL=1; I2CWait(); SCL=0; }
/*********发送NO ACK*********/ void I2CNoAck(void) { SDA=1; SCL=0; I2CWait(); SCL=1; I2CWait(); SCL=0; }
/********关闭SD2200的I2C总线*******/ void I2CStop(void) { SDA=0; SCL=0; I2CWait(); SCL=1; I2CWait(); SDA=1; }
/********开启SD2200的I2C总线********/ bit I2CStart(void) { SDA=1; SCL=1; I2CWait(); if(!SDA)return 0;//SDA线为低电平则总线忙,退出 SDA=0; I2CWait(); while(SDA)return 0;//SDA线为高电平则总线出错,退出 SCL=0; I2CWait(); return 1; }
/*********读取ACK信号*********/ bit I2CWaitAck(void) //返回为:1=有ACK,0=无ACK { uchar errtime=255; SCL=0; SDA=1; I2CWait(); SCL=1; I2CWait(); while(SDA) { errtime--; if(!errtime) SCL=0; return 0; } SCL=0; return 1; }
/* Function: I2CRead Return: 8-bit data read from I2C bus Arguments: Description: read 8-bit data from I2C bus */ unsigned char I2CRead(void) { unsigned char temp; /* Reception works if transfer is initiated in read mode */ RCEN = 1; /* Enable data reception */ while(!BF); /* wait for buffer full */ temp = SSPBUF; /* Read serial buffer and store in temp register */ I2CWait(); /* wait to check any pending transfer */ return temp; /* Return the read data from bus */ }
/*********MCU从SD2200读入一字节*********/ uchar I2CReceiveByte(void) { uchar i=8; uchar ddata=0; SDA=1; while(i--) { ddata>>=1; //数据从低位开始读取 SCL=0; I2CWait(); SCL=1; I2CWait(); //从低位开始 ddata|=SDA;ddata>>=1 if(SDA) { ddata|=0x80; } } SCL=0; return ddata; }
/* Function: I2CSend Return: Arguments: dat - 8-bit data to be sent on bus data can be either address/data byte Description: Send 8-bit data on I2C bus */ void I2CSend(unsigned char dat) { SSPBUF = dat; /* Move data to SSPBUF */ while(BF); /* wait till complete data is sent from buffer */ I2CWait(); /* wait for any pending transfer */ }