Skip to content

Instantly share code, notes, and snippets.

@paulc
Created October 28, 2020 00:25
Show Gist options
  • Select an option

  • Save paulc/c85e1c6a1a10c1ffc609eb473dbc2519 to your computer and use it in GitHub Desktop.

Select an option

Save paulc/c85e1c6a1a10c1ffc609eb473dbc2519 to your computer and use it in GitHub Desktop.
TinyGo / WioTerminal - Strange behaviour reading Accelerometer in goroutine
package main
import (
"fmt"
"image/color"
"machine"
"time"
"tinygo.org/x/drivers/ili9341"
"tinygo.org/x/drivers/lis3dh"
"tinygo.org/x/tinyfont"
"tinygo.org/x/tinyfont/proggy"
)
var (
display = ili9341.NewSPI(
machine.SPI3,
machine.LCD_DC,
machine.LCD_SS_PIN,
machine.LCD_RESET,
)
backlight = machine.LCD_BACKLIGHT
Black = color.RGBA{0, 0, 0, 255}
White = color.RGBA{255, 255, 255, 255}
Red = color.RGBA{255, 0, 0, 255}
Blue = color.RGBA{0, 0, 255, 255}
Green = color.RGBA{0, 255, 0, 255}
)
//
// Display
//
func InitDisplay() (width, height int16) {
machine.SPI3.Configure(machine.SPIConfig{
SCK: machine.LCD_SCK_PIN,
SDO: machine.LCD_SDO_PIN,
SDI: machine.LCD_SDI_PIN,
Frequency: 40000000,
})
display.Configure(ili9341.Config{})
display.SetRotation(ili9341.Rotation270)
display.FillScreen(color.RGBA{0, 0, 0, 255})
backlight.Configure(machine.PinConfig{machine.PinOutput})
backlight.High()
return display.Size()
}
func Status(msg string, fg color.RGBA, bg color.RGBA) {
display.FillRectangle(0, 0, 320, 16, bg)
tinyfont.WriteLine(display, &proggy.TinySZ8pt7b, 10, 10, msg, fg)
}
//
// Accelerometer
//
type Accel struct {
device lis3dh.Device
}
type AccelData struct {
X, Y, Z int32
}
func NewAccel(i2c machine.I2C, scl, sda machine.Pin) Accel {
i2c.Configure(machine.I2CConfig{SCL: scl, SDA: sda})
acc := Accel{device: lis3dh.New(i2c)}
acc.device.Configure()
return acc
}
func (a Accel) GetAccel() AccelData {
x, y, z, _ := a.device.ReadAcceleration()
return AccelData{X: x, Y: y, Z: z}
}
//
// Main loop
//
func main() {
InitDisplay()
acc := NewAccel(machine.I2C0, machine.PIN_WIRE1_SCL, machine.PIN_WIRE1_SDA)
c := make(chan AccelData)
go func() {
for {
a := acc.GetAccel()
// XXX Goroutine returns valid accel data if I include debug println
// XXX but fixed data if I dont (also doesnt work with simple chan
// XXX recv or range)
// XXX ????
println(fmt.Sprintf(">> x: %-8d y: %-8d z: %-8d", a.X, a.Y, a.Z))
c <- a
time.Sleep(time.Millisecond * 100)
}
}()
for {
select {
case a := <-c:
s := fmt.Sprintf(">> x: %-8d y: %-8d z: %-8d", a.X, a.Y, a.Z)
Status(s, White, Red)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment