Hey guys, I just got a gyroscope and I ran the code and it worked. Now I am trying to understand the code. These are the lines I am having a problem with:
MSB = readI2C(0x29);
LSB = readI2C(0x28);
x = ((MSB << 8) | LSB);
I understand the bitwise or symbol. But I cant understand why it is shifting the MSB(byte) left 8 spaces before comparing it.
Can anybody help me?
The or is not comparing it is combining. x is an integer (16 bits, 2 bytes). When you shift the MSB 8 bit the the left it is placed into the upper 8 bits of x then or-ed with the LSB which is placed into the lower 8 bits of x.
x starts out 00000000 00000000
shift in MSB (0xff) 11111111 00000000
or with LSB (0x33) 11111111 00110011
You are not comparing anything. You are putting two 8 bit numbers, which you got from the device , together to make a 16 bit number.
That is probably not the best way to do an I2C read. Most I2C libraries enable you to read several bytes from consecutive device register locations in a single read operation, which will save time.