1

I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go - this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val[1]) << 8) | int(val[2])" before getting the result.

Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

closed as off-topic by Juraj, sempaiscuba, VE7JRO, gre_gor, MatsK Apr 13 '18 at 13:05

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question does not appear to be about Arduino, within the scope defined in the help center." – Juraj, sempaiscuba, VE7JRO, gre_gor, MatsK
If this question can be reworded to fit the rules in the help center, please edit the question.

2

You read bytes in the order:

  • Most significant byte (let's call this msb)
  • Least significant byte (let's call this lsb)

The formula to get to real value is msb * 256 + lsb 256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).

However, a CPU is normally faster in bit operations than in arithmetic operations.

Assume msb is 10101010
and lsb is    11001100

Now below is the table with the calculation order

sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.

  • Great, thanks! But why is this only for the analog read? It doesn't seem like they do it for the digital one – lucavallin Apr 12 '18 at 14:20
  • I don't know ... it depends on the order in which the bytes are received. – Michel Keijzers Apr 12 '18 at 14:22
  • @lucavallin, I still think you do not know what you do. You write about analog, but there is nothing analog in that sensor's interface. – Juraj Apr 14 '18 at 19:36
  • @Juraj Thank you for your contribution, however I believe this community was created for people who do not know what they're doing. If I did I would have written a blog post instead of asking a question. – lucavallin Apr 17 '18 at 9:31
  • @lucavallin, but I could explain if you would disclose the type of the sensor – Juraj Apr 17 '18 at 10:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.