简体   繁体   English

需要说明acc_x = Wire.read()<< 8 | Wire.read();

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

what does wire.read()<<8|wire.read() do? wire.read()<< 8 | wire.read()有什么作用?

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. 从这段代码来看,我认为设备报告的加速度大于8位数字,也许是16位,但一次仅8位...因此,假设acc_x值在草图中定义为整数。 So we're filling a 16-bit value 8 bits at a time I'd guess... 所以我猜一次填充8位的16位值...

So, Wire.read() probably gets an 8-bit value. 因此, Wire.read()可能会获得8位值。 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 | 下一部分<<8将该值左移8位,有效地将其乘以256。第二个Wire.read与ed or ed与| , 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. 综上所述,通过从第一次读取中获取数字,将其左移以使其位更重要,然后对( or添加)第二次读取的结果来构建16位数字。

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. 就像您的标签所暗示的那样,这称为按位数学或按位操作,这在Arduino和所有微控制器平台上都很常见,这些平台的输入引脚排列为8位“端口”,并且这些设备的外设也很常见以提供其数据。每次一次为一个字节,以减少连接外设的引脚数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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