Use ustruct to reorganize byte values, Pandora development board gyroscope
[Copy link]
This post was last edited by zy459994202 on 2019-8-22 16:02
Recently, I have been using RT-Thread MicroPython to operate the Pandora development board to read the acceleration and angular velocity from the icm20608 sensor, which took a lot of effort.
I want to concatenate the byte data read from the register into a 16-bit integer and then print it out. However, I have encountered difficulties in concatenating the unsigned single-byte data read each time into a 16-bit integer.
The initial idea was to use bit operations to shift the read data, then concatenate them together and finally assign them to a variable. Eventually, I found that no matter how I used bit operations, I could not get a 16-bit signed integer data, because Python always uses a larger data structure to store the concatenated values, resulting in the final print result always being an unsigned positive number. Eventually, I found that to solve this problem, I had to use the struct module.
Before using this module to splice data, you must also figure out the big and small endianness of the data, that is, whether the byte data read out first is the high or low bit. If you do it the other way around, the final result will definitely be confusing. You will most likely see all kinds of inexplicable negative numbers.
Without further ado, let's get straight to the code. The following code implements the synthesis of two bytes into a sixteen-bit signed integer data.
buf=bytearray(2)
buf[0] = xyz[1]
buf[1] = xyz[0]
gyro_x = struct.unpack("<h", buf)
It is important to note the location of the data stored in buf[0] and buf[1], that is, the high and low bits must be clear, so that the correct data can be obtained after unpacking.
The following are the codes of various data:
- fmt:数据类型
- b — 字节型
- B — 无符号字节型
- h — 短整型
- H — 无符号短整型
- i — 整型
- I — 无符号整型
- l — 整型
- L — 无符号整型
- q — 长整型
- Q — 无符号长整型
- f — 浮点型
- d — 双精度浮点型
- P — 无符号型
|