rts-sim-testing-service/third_party/message/accelerometer.go

64 lines
1.3 KiB
Go
Raw Normal View History

2024-01-26 17:57:35 +08:00
package message
import (
"fmt"
2024-04-19 16:55:51 +08:00
"math"
2024-01-26 17:57:35 +08:00
)
const (
accHeader = 0xA6
uaidDefault = 0x1C
)
type Accelerometer struct {
2024-04-19 16:55:51 +08:00
Acc float32
Aux byte
2024-01-26 17:57:35 +08:00
}
2024-04-19 16:55:51 +08:00
const (
FullScaleG = 0x80000000 // 1g的Q31表示
DataMask = 0xC0 // 最高2位是数据位
ReadingMask = 0xFFFFC000 // 屏蔽标志位和编码位
)
2024-01-26 17:57:35 +08:00
func (acc *Accelerometer) Encode() []byte {
2024-04-19 16:55:51 +08:00
accData := uint32(math.Round(float64(acc.Acc) * float64(FullScaleG)))
d2 := byte(accData >> 16)
d1 := byte(accData >> 8)
D0 := byte(accData) & 0xFF
D0 |= byte((accData >> 18) & DataMask)
2024-01-26 17:57:35 +08:00
data := make([]byte, 0)
data = append(data, accHeader)
data = append(data, uaidDefault)
2024-04-19 16:55:51 +08:00
data = append(data, D0)
data = append(data, d1)
data = append(data, d2)
data = append(data, acc.Aux)
2024-01-26 17:57:35 +08:00
cs := checkSum(data)
data = append(data, ^cs+1)
return data
2024-04-19 16:55:51 +08:00
2024-01-26 17:57:35 +08:00
}
func checkSum(data []byte) byte {
var sum byte = 0
for _, d := range data {
sum += d
}
return sum
}
2024-04-19 16:55:51 +08:00
func (acc *Accelerometer) Decode(Packet []byte) error {
if len(Packet) < 7 {
2024-01-26 17:57:35 +08:00
return fmt.Errorf("")
}
2024-04-19 16:55:51 +08:00
data := uint32(Packet[4])<<16 | uint32(Packet[3])<<8 | uint32(Packet[2])
// 应用屏蔽以移除标志位和编码位
data &= ReadingMask
// 将Q31值转换为float32加速度值g
acceleration := float32(float32(data) * (1.0 / float32(FullScaleG)))
fmt.Println(acceleration)
2024-01-26 17:57:35 +08:00
return nil
}