Skip to main content
BKem.1
Associate II
June 5, 2020
Question

Reading I2C bits with STM32F4Discovery

  • June 5, 2020
  • 3 replies
  • 2285 views

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

 }

This topic has been closed for replies.

3 replies

Tesla DeLorean
Guru
June 5, 2020

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 (See Profile) Up vote any posts that you find helpful, it shows what's working..
BKem.1
BKem.1Author
Associate II
June 8, 2020

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

TDK
June 5, 2020

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""."
Piranha
Principal III
June 11, 2020

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