uint8 HalI2CReadSingle(uint8 addr) { uint8 ret = 0xFF; if (i2cMstStrt(0) != mstAddrAckW) { I2C_STOP(); return ret; } I2C_WRITE(addr); if (I2CSTAT != mstDataAckW) { I2C_STOP(); return ret; } if (i2cMstRepeatedStrt(I2C_MST_RD_BIT) != mstAddrAckR) { I2C_STOP(); return ret; } I2C_SET_NACK(); // read a byte from the I2C interface I2C_READ(ret); if (I2CSTAT != mstDataNackR) { ret = 0xFF; } I2C_STOP(); return ret; }
/************************************************************************************************** * @fn HalI2CRead * * @brief Read from the I2C bus as a Master. * * input parameters * * @param len - Number of bytes to read. * @param pBuf - Pointer to the data buffer to put read bytes. * * output parameters * * None. * * @return The number of bytes successfully read. */ uint8 HalI2CRead(uint8 len, uint8 *pBuf) { uint8 cnt = 0; if (i2cMstStrt(I2C_MST_RD_BIT) != mstAddrAckR) { len = 0; } // All bytes are ACK'd except for the last one which is NACK'd. If only // 1 byte is being read, a single NACK will be sent. Thus, we only want // to enable ACK if more than 1 byte is going to be read. if (len > 1) { I2C_SET_ACK(); } while (len > 0) { // slave devices require NACK to be sent after reading last byte if (len == 1) { I2C_SET_NACK(); } // read a byte from the I2C interface I2C_READ(*pBuf++); cnt++; len--; if (I2CSTAT != mstDataAckR) { if (I2CSTAT != mstDataNackR) { // something went wrong, so don't count last byte cnt--; } break; } } I2C_STOP(); return cnt; }