简体   繁体   中英

need explanation acc_x = Wire.read()<<8|Wire.read();

what does wire.read()<<8|wire.read() do?

while(Wire.available() < 14);                                        
until all the bytes are received
 acc_x = Wire.read()<<8|Wire.read();                                  
 acc_y = Wire.read()<<8|Wire.read();                                   
 acc_z = Wire.read()<<8|Wire.read();                                  
 temp = Wire.read()<<8|Wire.read();                                   
 gyro_x = Wire.read()<<8|Wire.read();                                 
 gyro_y = Wire.read()<<8|Wire.read();                                 
 gyro_z = Wire.read()<<8|Wire.read();

Judging from this code I'd say the device reports acceleration as more than an 8-bit number, perhaps 16 bits, but only 8 bits at a time...so assuming the acc_x value is defined as an integer in your sketch. So we're filling a 16-bit value 8 bits at a time I'd guess...

So, Wire.read() probably gets an 8-bit value. The next part <<8 shifts that value, eight bits left, effectively multiplying it by 256. The second Wire.read is or ed with the first with | , effectively adding it to the first byte. This read-shift-or process is repeated for every measure the device supplies.

00001010 // let's assume this is the result of the first read
<<8 gives 00001010_00000000
00001111  // let's assume this is the result of the second read
00001010_00000000 | 00001111  // | has the effect of adding here

gives 00001010_00001111 //final acceleration value

So to recap, the 16-bit number is built up by taking the number from the first read, left-shifting it to make its bits more significant, then or ing (adding) the result of the second read.

As your tag suggests, this is called bitwise math or bitwise manipulation and it's very common on Arduino and all microcontroller platforms which have input pins arranged in 8-bit "ports," and it's also common for peripherals for these devices to supply their data one byte at a time like this so as to reduce the number of pins to interface the peripheral.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM