Skip to main content
JHERI
Associate III
October 8, 2021
Solved

Why is this not working ??

  • October 8, 2021
  • 5 replies
  • 988 views

Hi guys

I have a real strange issue

trying to move two 8bits values in to one 16bit variable,

can someone please tell me why this does not work

It should OR the lsb to the msb

      Sensor_Flow = I2C1_DATA[0] ;

      Sensor_Flow = Sensor_Flow << 8;

      Sensor_Flow = Sensor_Flow || I2C1_DATA[1];

thanks in addvance

This topic has been closed for replies.
Best answer by Tesla DeLorean

Simpler, less prone to be wrong..

Sensor_Flow = ((uint16_t)I2C1_DATA[0] << 8) + (uint16_t)I2C1_DATA[1];

5 replies

PatrickF
ST Employee
October 8, 2021

Hi,

you mixed up || (logical OR) and | (binary OR), please try :

      Sensor_Flow = Sensor_Flow | I2C1_DATA[1];

assuming I2C1_DATA[ ] is defined as bytes array, otherwise need to mask to get only LSByte (i.e. I2C1_DATA[x] & 0xFF) .

Regards,

In order to give better visibility on the answered topics, please click on 'Select as Best' on the reply which solved your issue or answered your question. See also 'Best Answers'

In order to give better visibility on the answered topics, please click on 'Best Answer' on the reply which solved your issue or answered your question.Tip of the day: Try Sidekick STM32 AI agent
Javier1
Principal
October 8, 2021

if sensor_flow is uint16_t and I2C_DATA is a uint8_t or char array....

you could also try

memcpy(&Sensor_Flow, &I2C_DATA[0],2);//2=2bytes

hit me up in https://www.linkedin.com/in/javiermuñoz/
JHERI
JHERIAuthor
Associate III
October 8, 2021

Thanks guys

Just coming back to C after a long break,

Doh back to the drawing board :(

Regards

JHERI
JHERIAuthor
Associate III
October 8, 2021

Hi guys

don't think mem copy will work as my first byte of data [0] is the msb and byte 2 [1] is lsb

It create the 16bit data variable with the byte order wrong

though I like the simplistic approach

Regards

Tesla DeLorean
Tesla DeLoreanBest answer
Guru
October 8, 2021

Simpler, less prone to be wrong..

Sensor_Flow = ((uint16_t)I2C1_DATA[0] << 8) + (uint16_t)I2C1_DATA[1];

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