-
Notifications
You must be signed in to change notification settings - Fork 110
/
mpu6050.go
337 lines (288 loc) · 10.2 KB
/
mpu6050.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Package mpu6050 implements the movementsensor interface for an MPU-6050 6-axis accelerometer.
package mpu6050
import (
"context"
"encoding/binary"
"math"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/golang/geo/r3"
geo "github.com/kellydunn/golang-geo"
"github.com/pkg/errors"
"go.viam.com/utils"
"go.viam.com/rdk/components/board"
"go.viam.com/rdk/components/generic"
"go.viam.com/rdk/components/movementsensor"
"go.viam.com/rdk/config"
"go.viam.com/rdk/registry"
"go.viam.com/rdk/spatialmath"
rutils "go.viam.com/rdk/utils"
)
const modelName = "gyro-mpu6050"
// AttrConfig is used to configure the attributes of the chip.
type AttrConfig struct {
BoardName string `json:"board"`
BusID string `json:"bus_id"`
UseAlternateI2CAddress bool `json:"use_alt_i2c_address,omitempty"`
}
// Validate ensures all parts of the config are valid, and then returns the list of things we
// depend on.
func (cfg *AttrConfig) Validate(path string) ([]string, error) {
if cfg.BoardName == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "board")
}
if cfg.BusID == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "bus_id")
}
var deps []string
deps = append(deps, cfg.BoardName)
return deps, nil
}
func init() {
registry.RegisterComponent(movementsensor.Subtype, modelName, registry.Component{
// Note: this looks like it can be simplified to just be `Constructor: NewMpu6050`.
// However, if you try that, the compiler says the types are subtly incompatible. Just
// leave it like this.
Constructor: func(
ctx context.Context,
deps registry.Dependencies,
cfg config.Component,
logger golog.Logger,
) (interface{}, error) {
return NewMpu6050(ctx, deps, cfg, logger)
},
})
config.RegisterComponentAttributeMapConverter(movementsensor.SubtypeName, modelName,
func(attributes config.AttributeMap) (interface{}, error) {
var attr AttrConfig
return config.TransformAttributeMapToStruct(&attr, attributes)
},
&AttrConfig{})
}
type mpu6050 struct {
bus board.I2C
i2cAddress byte
mu sync.Mutex
// The 3 things we can measure: lock the mutex before reading or writing these.
angularVelocity spatialmath.AngularVelocity
temperature float64
linearAcceleration r3.Vector
// Stores the most recent error from the background goroutine
lastError error
// Used to shut down the background goroutine which polls the sensor.
backgroundContext context.Context
cancelFunc func()
activeBackgroundWorkers sync.WaitGroup
logger golog.Logger
generic.Unimplemented // Implements DoCommand with an ErrUnimplemented response
}
// NewMpu6050 constructs a new Mpu6050 object.
func NewMpu6050(
ctx context.Context,
deps registry.Dependencies,
rawConfig config.Component,
logger golog.Logger,
) (movementsensor.MovementSensor, error) {
cfg, ok := rawConfig.ConvertedAttributes.(*AttrConfig)
if !ok {
return nil, rutils.NewUnexpectedTypeError(cfg, rawConfig.ConvertedAttributes)
}
b, err := board.FromDependencies(deps, cfg.BoardName)
if err != nil {
return nil, err
}
localB, ok := b.(board.LocalBoard)
if !ok {
return nil, errors.Errorf("board %s is not local", cfg.BoardName)
}
bus, ok := localB.I2CByName(cfg.BusID)
if !ok {
return nil, errors.Errorf("can't find I2C bus '%s' for MPU6050 sensor", cfg.BusID)
}
var address byte
if cfg.UseAlternateI2CAddress {
address = 0x69
} else {
address = 0x68
}
logger.Debugf("Using address %d for MPU6050 sensor", address)
backgroundContext, cancelFunc := context.WithCancel(ctx)
sensor := &mpu6050{
bus: bus,
i2cAddress: address,
logger: logger,
backgroundContext: backgroundContext,
cancelFunc: cancelFunc,
}
// To check that we're able to talk to the chip, we should be able to read register 117 and get
// back the device's non-alternative address (0x68)
defaultAddress, err := sensor.readByte(ctx, 117)
if err != nil {
return nil, errors.Errorf("can't read from I2C address %d on bus %s of board %s: '%s'",
address, cfg.BusID, cfg.BoardName, err.Error())
}
if defaultAddress != 0x68 {
return nil, errors.Errorf("unexpected non-MPU6050 device at address %d: response '%d'",
address, defaultAddress)
}
// The chip starts out in standby mode (the Sleep bit in the power management register defaults
// to 1). Set it to measurement mode (by turning off the Sleep bit) so we can get data from it.
// To do this, we set register 107 to 0.
err = sensor.writeByte(ctx, 107, 0)
if err != nil {
return nil, errors.Errorf("Unable to wake up MPU6050: '%s'", err.Error())
}
// Now, turn on the background goroutine that constantly reads from the chip and stores data in
// the object we created.
sensor.activeBackgroundWorkers.Add(1)
utils.PanicCapturingGo(sensor.pollData)
return sensor, nil
}
func (mpu *mpu6050) readByte(ctx context.Context, register byte) (byte, error) {
result, err := mpu.readBlock(ctx, register, 1)
if err != nil {
return 0, err
}
return result[0], err
}
func (mpu *mpu6050) readBlock(ctx context.Context, register byte, length uint8) ([]byte, error) {
handle, err := mpu.bus.OpenHandle(mpu.i2cAddress)
if err != nil {
return nil, err
}
defer func() {
err := handle.Close()
if err != nil {
mpu.logger.Error(err)
}
}()
results, err := handle.ReadBlockData(ctx, register, length)
return results, err
}
func (mpu *mpu6050) writeByte(ctx context.Context, register, value byte) error {
handle, err := mpu.bus.OpenHandle(mpu.i2cAddress)
if err != nil {
return err
}
defer func() {
err := handle.Close()
if err != nil {
mpu.logger.Error(err)
}
}()
return handle.WriteByteData(ctx, register, value)
}
// A helper function: takes 2 bytes and reinterprets them as a big-endian signed integer.
func toSignedValue(data []byte) int {
return int(int16(binary.BigEndian.Uint16(data)))
}
// Given a value, scales it so that the range of int16s becomes the range of +/- maxValue.
func setScale(value int, maxValue float64) float64 {
return float64(value) * maxValue / (1 << 15)
}
// A helper function to abstract out shared code: takes 6 bytes and gives back AngularVelocity, in
// radians per second.
func toAngularVelocity(data []byte) spatialmath.AngularVelocity {
gx := toSignedValue(data[0:2])
gy := toSignedValue(data[2:4])
gz := toSignedValue(data[4:6])
maxRotation := 250.0 // Maximum degrees per second measurable in the default configuration
radiansPerDegree := math.Pi / 180.0
return spatialmath.AngularVelocity{
X: setScale(gx, maxRotation*radiansPerDegree),
Y: setScale(gy, maxRotation*radiansPerDegree),
Z: setScale(gz, maxRotation*radiansPerDegree),
}
}
// A helper function that takes 6 bytes and gives back linear acceleration.
func toLinearAcceleration(data []byte) r3.Vector {
x := toSignedValue(data[0:2])
y := toSignedValue(data[2:4])
z := toSignedValue(data[4:6])
// The scale is +/- 2G's, but our units should be mm/sec/sec.
maxAcceleration := 2.0 * 9.81 /* m/sec/sec */ * 1000.0 /* mm/m */
return r3.Vector{
X: setScale(x, maxAcceleration),
Y: setScale(y, maxAcceleration),
Z: setScale(z, maxAcceleration),
}
}
func (mpu *mpu6050) pollData() {
defer mpu.activeBackgroundWorkers.Done()
// Reading data a thousand times per second is probably fast enough.
timer := time.NewTicker(time.Millisecond)
defer timer.Stop()
for {
select {
case <-mpu.backgroundContext.Done():
return
case <-timer.C:
rawData, err := mpu.readBlock(mpu.backgroundContext, 59, 14)
if err != nil {
mpu.logger.Infof("error reading MPU6050 sensor: '%s'", err)
mpu.mu.Lock()
mpu.lastError = err
mpu.mu.Unlock()
continue
}
linearAcceleration := toLinearAcceleration(rawData[0:6])
// Taken straight from the MPU6050 register map. Yes, these are weird constants.
temperature := float64(toSignedValue(rawData[6:8]))/340.0 + 36.53
angularVelocity := toAngularVelocity(rawData[8:14])
// Lock the mutex before modifying the state within the object. By keeping the mutex
// unlocked for everything else, we maximize the time when another thread can read the
// values.
mpu.mu.Lock()
mpu.linearAcceleration = linearAcceleration
mpu.temperature = temperature
mpu.angularVelocity = angularVelocity
mpu.mu.Unlock()
}
}
}
func (mpu *mpu6050) AngularVelocity(ctx context.Context, extra map[string]interface{}) (spatialmath.AngularVelocity, error) {
mpu.mu.Lock()
defer mpu.mu.Unlock()
return mpu.angularVelocity, nil
}
func (mpu *mpu6050) LinearVelocity(ctx context.Context, extra map[string]interface{}) (r3.Vector, error) {
return r3.Vector{}, movementsensor.ErrMethodUnimplementedLinearVelocity
}
func (mpu *mpu6050) Orientation(ctx context.Context, extra map[string]interface{}) (spatialmath.Orientation, error) {
return nil, movementsensor.ErrMethodUnimplementedOrientation
}
func (mpu *mpu6050) CompassHeading(ctx context.Context, extra map[string]interface{}) (float64, error) {
return 0, movementsensor.ErrMethodUnimplementedCompassHeading
}
func (mpu *mpu6050) Position(ctx context.Context, extra map[string]interface{}) (*geo.Point, float64, error) {
return geo.NewPoint(0, 0), 0, movementsensor.ErrMethodUnimplementedPosition
}
func (mpu *mpu6050) Accuracy(ctx context.Context, extra map[string]interface{}) (map[string]float32, error) {
return map[string]float32{}, movementsensor.ErrMethodUnimplementedAccuracy
}
func (mpu *mpu6050) Readings(ctx context.Context, extra map[string]interface{}) (map[string]interface{}, error) {
mpu.mu.Lock()
defer mpu.mu.Unlock()
readings := make(map[string]interface{})
readings["linear_acceleration"] = mpu.linearAcceleration
readings["temperature_celsius"] = mpu.temperature
readings["angular_velocity"] = mpu.angularVelocity
return readings, nil
}
func (mpu *mpu6050) Properties(ctx context.Context, extra map[string]interface{}) (*movementsensor.Properties, error) {
return &movementsensor.Properties{
AngularVelocitySupported: true,
}, nil
}
func (mpu *mpu6050) Close(ctx context.Context) {
mpu.mu.Lock()
defer mpu.mu.Unlock()
mpu.cancelFunc()
mpu.activeBackgroundWorkers.Wait()
// Set the Sleep bit (bit 6) in the power control register (register 107).
err := mpu.writeByte(ctx, 107, 1<<6)
if err != nil {
mpu.logger.Error(err)
}
}