cancel
Showing results for 
Search instead for 
Did you mean: 

Why is this not working ??

JHERI
Senior

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

1 ACCEPTED SOLUTION

Accepted Solutions

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
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

5 REPLIES 5
PatrickF
ST Employee

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 'Accept as Solution' on the reply which solved your issue or answered your question.
Javier1
Principal

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

we dont need to firmware by ourselves, lets talk
JHERI
Senior

Thanks guys

Just coming back to C after a long break,

Doh back to the drawing board :(

Regards

JHERI
Senior

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

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
Up vote any posts that you find helpful, it shows what's working..