nicebadge/tutorial/basics/step9/main.go

66 lines
1.4 KiB
Go
Raw Normal View History

2026-04-18 11:01:06 +00:00
package main
import (
"machine"
"time"
2026-04-19 16:29:28 +00:00
"tinygo.org/x/drivers/encoders"
2026-04-18 11:01:06 +00:00
)
2026-04-19 16:29:28 +00:00
const deadzone = 5000
2026-04-18 11:01:06 +00:00
2026-04-19 16:29:28 +00:00
func main() {
2026-04-18 11:01:06 +00:00
btnA := machine.P1_06
btnB := machine.P1_04
2026-04-19 16:29:28 +00:00
btnC := machine.P0_22 // rotary encoder push button
2026-04-18 11:01:06 +00:00
btnA.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
btnB.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
2026-04-19 16:29:28 +00:00
btnC.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
enc := encoders.NewQuadratureViaInterrupt(machine.P1_00, machine.P0_24)
enc.Configure(encoders.QuadratureConfig{Precision: 4})
2026-04-18 11:01:06 +00:00
2026-04-19 16:29:28 +00:00
machine.InitADC()
ax := machine.ADC{Pin: machine.P0_02}
ay := machine.ADC{Pin: machine.P0_29}
ax.Configure(machine.ADCConfig{})
ay.Configure(machine.ADCConfig{})
prevA := true
prevB := true
prevC := true
prevPos := enc.Position()
2026-04-18 11:01:06 +00:00
for {
2026-04-19 16:29:28 +00:00
a := btnA.Get()
b := btnB.Get()
c := btnC.Get()
if !a && prevA {
println("button A pressed")
}
if !b && prevB {
println("button B pressed")
2026-04-18 11:01:06 +00:00
}
2026-04-19 16:29:28 +00:00
if !c && prevC {
println("encoder button pressed")
2026-04-18 11:01:06 +00:00
}
2026-04-19 16:29:28 +00:00
prevA = a
prevB = b
prevC = c
pos := enc.Position()
if pos != prevPos {
println("encoder:", pos)
prevPos = pos
2026-04-18 11:01:06 +00:00
}
2026-04-19 16:29:28 +00:00
rawX := int(ax.Get()) - 32767
rawY := int(ay.Get()) - 32767
if rawX > deadzone || rawX < -deadzone || rawY > deadzone || rawY < -deadzone {
println("joystick:", "x=", rawX, "y=", rawY)
2026-04-18 11:01:06 +00:00
}
2026-04-19 16:29:28 +00:00
time.Sleep(50 * time.Millisecond)
2026-04-18 11:01:06 +00:00
}
}