cancel
Showing results for 
Search instead for 
Did you mean: 

Reading I2C bits with STM32F4Discovery

BKem.1
Associate II

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:

0693W000001q9ZIQAY.png

All I have now is this code:

0693W000001q9ZSQAY.png 

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);

 }

5 REPLIES 5

val = ((int16_t)(buf[0] & 0x3F) << 8) | ((int16_t)buf[1] ); 

if (val & 0x2000) val |= 0xC000; // Sign Extend

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
TDK
Guru

Humidity can't be negative. I don't think the "sign extend" line is desired.

If you feel a post has answered your question, please click "Accept as Solution".

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

Especially, where is the 0x3F byte from? What would happen, if I Would change its value?

Piranha
Chief II

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...