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?

8
  • 5
    ... Because you read one byte at a time. – Ignacio Vazquez-Abrams Apr 12 '18 at 7:05
  • Can you be more specific? When Read() is called, my array of bytes is filled right away, why do I need this operation afterwards? – user45703 Apr 12 '18 at 7:13
  • Because now you need a number. 123 = 100 + 20 + 3 – Ignacio Vazquez-Abrams Apr 12 '18 at 7:14
  • Alright, but why are we not using the first 4 bytes? – user45703 Apr 12 '18 at 7:32
  • @lucavallin This seems to be a good documentation of the protocol; dexterindustries.com/GrovePi/programming/… – Mikael Patel Apr 12 '18 at 8:46
1

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.

6
  • Great, thanks! But why is this only for the analog read? It doesn't seem like they do it for the digital one – user45703 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. – user45703 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