Created
March 17, 2020 12:20
-
-
Save kianryan/f5a0e9a86e722ac606e0f3e9dfed12b5 to your computer and use it in GitHub Desktop.
tinygo demo for BBC MicroBit using accelerometer and matrix display
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
"machine" | |
"image/color" | |
"tinygo.org/x/drivers/microbitmatrix" | |
"tinygo.org/x/drivers/mma8653" | |
) | |
var i2c mma8653.Device | |
var display microbitmatrix.Device | |
func main() { | |
// The ic2 bus must already be configured. | |
machine.I2C0.Configure(machine.I2CConfig{}) | |
accel := mma8653.New(machine.I2C0) | |
accel.Configure(mma8653.DataRate200Hz, mma8653.Sensitivity2G) | |
display = microbitmatrix.New() | |
display.Configure(microbitmatrix.Config{}) | |
display.ClearDisplay() | |
x := int16(1) | |
y := int16(2) | |
c := color.RGBA{255, 255, 255, 255} | |
threshold := int32(1000000 / 2) | |
then := time.Now() | |
for { | |
// Must use time and since - delay is blocking. | |
if time.Since(then).Nanoseconds() > 80000000 { | |
then = time.Now() | |
println("hello world!") | |
// pointing straight to Earth | |
// and the sensor is not moving the returned value will be around 1000000 or | |
// -1000000. | |
ax, ay, _, _ := accel.ReadAcceleration() | |
print("Ax:") | |
println(ax) | |
print("Ay:") | |
println(ay) | |
// if we're rotating on the x axis, then inc y. | |
if Abs(ax) > threshold { | |
if ax > 0 && y < 4 { | |
y = y + 1 | |
} else if ax < 0 && y > 0 { | |
y = y - 1 | |
} | |
} | |
if Abs(ay) > threshold { | |
if ay > 0 && x < 4 { | |
x = x + 1 | |
} else if ay < 0 && x > 0 { | |
x = x - 1 | |
} | |
} | |
display.ClearDisplay() | |
display.SetPixel(x, y, c) | |
} | |
display.Display() | |
} | |
} | |
func Abs(x int32) int32 { | |
if x < 0 { | |
return -x | |
} | |
return x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment