Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save floppyzedolfin/acde56a9c265291413aacc654675d5f2 to your computer and use it in GitHub Desktop.
Save floppyzedolfin/acde56a9c265291413aacc654675d5f2 to your computer and use it in GitHub Desktop.
package main
import (
"machine"
"time"
)
func main() {
println("Hello, TinyGo")
cr := &crossroad{
car: newCar(),
walk: newWalk(),
button: newButton(),
buttonPressed: make(chan struct{}, 1),
}
cr.run()
}
type crossroad struct {
car carAmpel
walk walkAmpel
button buttonAmpel
buttonPressed chan struct{}
}
func (c *crossroad) run() {
go c.listenButton()
for {
c.car.Go()
select {
// We must have a maximum delay for pedestrians
case <- time.Tick(time.Second * 10):
c.allowWalk()
case <- c.buttonPressed:
c.allowWalk()
}
}
}
type buttonAmpel struct {
button machine.Pin // A6
}
func newButton() buttonAmpel {
b := buttonAmpel {
button: machine.A6,
}
b.button.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
return b
}
func (c *crossroad) listenButton() {
var lastState bool
for {
state := !c.button.button.Get() // button is pressed when pin is low
if state != lastState {
if state {
c.buttonPressed <- struct{}{}
}
lastState = state
}
time.Sleep(50 * time.Millisecond) // debounce delay
}
}
func (c *crossroad) allowWalk() {
c.car.Stop()
c.walk.Go()
time.Sleep(time.Second * 5)
c.walk.Stop()
// Allow pedestrians to finish crossing the street
time.Sleep(time.Second * 1)
}
type carAmpel struct {
red, yellow, green machine.Pin // A0, A1, A2
}
func newCar() carAmpel {
c := carAmpel {
red: machine.A0,
yellow: machine.A1,
green: machine.A2,
}
c.red.Configure(machine.PinConfig{Mode: machine.PinOutput})
c.yellow.Configure(machine.PinConfig{Mode: machine.PinOutput})
c.green.Configure(machine.PinConfig{Mode: machine.PinOutput})
c.red.High()
c.yellow.Low()
c.green.Low()
return c
}
func (c *carAmpel) Stop() {
c.green.Low()
c.yellow.High()
time.Sleep(time.Second)
c.yellow.Low()
c.red.High()
}
func (c *carAmpel) Go() {
c.red.High()
c.yellow.High()
time.Sleep(time.Second)
c.red.Low()
c.yellow.Low()
c.green.High()
}
type walkAmpel struct {
red, green machine.Pin // A4, A5
}
func newWalk() walkAmpel {
w := walkAmpel {
red: machine.A4,
green: machine.A5,
}
w.red.Configure(machine.PinConfig{Mode: machine.PinOutput})
w.green.Configure(machine.PinConfig{Mode: machine.PinOutput})
w.red.High()
w.green.Low()
return w
}
func (w *walkAmpel) Stop() {
for i:=0; i<5; i++{
w.green.Low()
time.Sleep(time.Millisecond*300)
w.green.High()
time.Sleep(time.Millisecond*300)
}
w.green.Low()
w.red.High()
}
func (w *walkAmpel) Go() {
w.red.Low()
w.green.High()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment