uint16_t readSensor(int SLAVE_READ_ADDRESS,int SLAVE_WRITE_ADDRESS) { int8_t success = FALSE; uint16_t data = 0; do { // Send the start bit with the restart flag low if(!I2C_startTransfer(ENCODER_I2C_ID, I2C_WRITE )){ #ifdef DEBUG printf("FAILED initial transfer!\n"); #endif break; } // Transmit the slave's address to notify it if (!I2C_sendData(ENCODER_I2C_ID, SLAVE_WRITE_ADDRESS)) break; // Tranmit the read address module if(!I2C_sendData(ENCODER_I2C_ID,SLAVE_ANGLE_ADDRESS)){ #ifdef DEBUG printf("Error: Sent byte was not acknowledged\n"); #endif break; } // Send a Repeated Started condition if(!I2C_startTransfer(ENCODER_I2C_ID,I2C_READ)){ #ifdef DEBUG printf("FAILED Repeated start!\n"); #endif break; } // Transmit the address with the READ bit set if (!I2C_sendData(ENCODER_I2C_ID, SLAVE_READ_ADDRESS)) break; // Read the I2C bus twice data = (I2C_getData(ENCODER_I2C_ID) << 6); I2C_acknowledgeRead(ENCODER_I2C_ID, TRUE); while(!I2C_hasAcknowledged(ENCODER_I2C_ID)); data |= (I2C_getData(ENCODER_I2C_ID) & 0x3F); // Send the stop bit to finish the transfer I2C_stopTransfer(ENCODER_I2C_ID); success = TRUE; } while(0); if (!success) { #ifdef DEBUG printf("Data transfer unsuccessful.\n"); #endif return FALSE; } return data; }
static uint16_t readDevice(uint8_t deviceReadAddress, uint8_t deviceWriteAddress, uint8_t dataAddress) { char success = FALSE; uint16_t data = 0; do { // Send the start bit with the restart flag low if(!I2C_startTransfer(ENCODER_I2C_ID, I2C_WRITE )){ DBPRINT("Encoder: FAILED initial transfer!\n"); break; } // Transmit the slave's address to notify it if (!I2C_sendData(ENCODER_I2C_ID, deviceWriteAddress)) break; // Tranmit the read address module if(!I2C_sendData(ENCODER_I2C_ID, dataAddress)){ DBPRINT("Encoder: Error: Sent byte was not acknowledged\n"); break; } // Send a Repeated Started condition if(!I2C_startTransfer(ENCODER_I2C_ID,I2C_READ)){ DBPRINT("Encoder: FAILED Repeated start!\n"); break; } // Transmit the address with the READ bit set if (!I2C_sendData(ENCODER_I2C_ID, deviceReadAddress)) break; // Read the I2C bus twice data = (I2C_getData(ENCODER_I2C_ID) << 6); I2C_acknowledgeRead(ENCODER_I2C_ID, TRUE); while(!I2C_hasAcknowledged(ENCODER_I2C_ID)); data |= (I2C_getData(ENCODER_I2C_ID) & 0x3F); // Send the stop bit to finish the transfer I2C_stopTransfer(ENCODER_I2C_ID); success = TRUE; } while(0); if (!success) { DBPRINT("Encoder: Data transfer unsuccessful.\n"); return FALSE; } return data; }