/* * This function reads one byte from the slave device * * Parameters: * ack - Flag to indicate either to send the acknowledge * message to the slave device or not * * Return Value: * One byte data read from the Slave device */ static unsigned char swI2CReadByte(unsigned char ack) { int i; unsigned char data = 0; for(i=7; i>=0; i--) { /* Set the SCL to Low and SDA to High (Input) */ swI2CSCL(0); swI2CSDA(1); swI2CWait(); /* Set the SCL High */ swI2CSCL(1); swI2CWait(); /* Read data bits from SDA */ data |= (swI2CReadSDA() << i); } if (ack) swI2CAck(); /* Set the SCL Low and SDA High */ swI2CSCL(0); swI2CSDA(1); return data; }
/******************************************************************************* swI2CWriteByte This function writes one byte to the slave device Parameters: data - Data to be write to the slave device Return Value: 0 - Fail to write byte 1 - Success *******************************************************************************/ unsigned char swI2CWriteByte(unsigned char data) { unsigned char value = data; int i; /* Sending the data bit by bit */ for (i=0; i<8; i++) { /* Set SCL to low */ swI2CSCL(0); /* Send data bit */ if ((value & 0x80) != 0) swI2CSDA(1); else swI2CSDA(0); swI2CWait(); /* Toggle clk line to one */ swI2CSCL(1); /* Shift byte to be sent */ value = value << 1; } /* Set the SCL Low and SDA High (prepare to get input) */ swI2CSCL(0); swI2CSDA(1); /* Set the SCL High for ack */ swI2CWait(); swI2CSCL(1); /* Read SDA, until SDA==0 */ for(i=0; i<0xff; i++) { swI2CWait(); swI2CWait(); if (!swI2CReadSDA()) break; } /* Set the SCL Low and SDA High */ swI2CSCL(0); swI2CSDA(1); return (i<0xff); }
/* * This function sends the stop command to the slave device */ static void swI2CStop(void) { /* Stop the I2C */ swI2CSCL(1); swI2CSDA(0); swI2CSDA(1); }
/* * This function sends the start command to the slave device */ static void swI2CStart(void) { /* Start I2C */ swI2CSDA(1); swI2CSCL(1); swI2CSDA(0); }
/******************************************************************************* swI2CStop This function sends the stop command to the slave device Parameters: None Return value: None *******************************************************************************/ void swI2CStop() { /* Stop the I2C */ swI2CSCL(1); swI2CSDA(0); swI2CSDA(1); }