2020-06-05 07:02 AM
Hello. I have the following scheme for reading the output of humidity sensor that communicates via I2C:
How would I execute this sequence with STM32CubeMX IDE and HAL libraries? The output of the sensor is as follows:
All I have now is this code:
uint8_t buf[2]; // 2 bytes? how to get 14 bits?
while (1)
{
if (HAL_I2C_IsDeviceReady(&hi2c1, 78, 5, 10) == HAL_OK){
res = HAL_I2C_Master_Transmit(&hi2c1, 78, 0, 2, 5); // start the writing cycle with bit 0;
if (res == HAL_OK){
res = HAL_I2C_Master_Receive(&hi2c1, 78, buf, 2, 10);
if (res == HAL_OK){
val = ((int16_t)buf[0] << 4) | (buf[1] >> 4); // how to combine these bytes?
if ( val > 0x7FF ) {
val |= 0xF000;
}
}
}
}
HAL_Delay(100);
}
2020-06-05 08:53 AM
val = ((int16_t)(buf[0] & 0x3F) << 8) | ((int16_t)buf[1] );
if (val & 0x2000) val |= 0xC000; // Sign Extend
2020-06-05 04:06 PM
Humidity can't be negative. I don't think the "sign extend" line is desired.
2020-06-08 01:25 AM
This seems to work, although the final measurement value is a bit off from what we have in the room. Could You explain, what You did with the first line of code? Thank You very much
2020-06-08 02:45 AM
Especially, where is the 0x3F byte from? What would happen, if I Would change its value?
2020-06-11 12:07 AM
It should be noted that these separate write+read operations put stop-start bit sequence in the middle. HAL_I2C_Mem_Read() can do a complete sequence, but it works only with memory/register addresses. HAL has those "Seq" functions - probably you can cobble it together with that crap. But all of this is ridiculous for a "high-level" library...