Reputation: 748
While going through my coursework, I came across a function that reads temperature from the TMP102 sensor (only required to measure positive temperatures).
The function first reads the MSB and LSB using I2C. Since the temperature data is 12-bit and left-justified, the function proceeds as follows:
temp = ( (MSB << 8) | LSB) >> 4
I do not understand why this is done. Could someone please help me explain how the above line of code is related to the data being 12-bit and left-justified?
Upvotes: 2
Views: 5863
Reputation:
Let v
be a bit of the temperature value and p
be a padding bit on the right, then you have
MSB = vvvvvvvv
LSB = vvvvpppp
---
MSB << 8 = vvvvvvvv 00000000
(MSB << 8) | LSB = vvvvvvvv vvvvpppp
((MSB << 8) | LSB) >> 4 = 0000vvvv vvvvvvvv
In the last line, you see the correct representation as a 16bit value (with the upper 4 bits always 0
).
Upvotes: 7