https://gist.github.com/tzechienchu/3685e7a2b6680b86f11eaaa4bc03e98c
func pinDebounce(
done <-chan interface{},
pin machine.Pin,
delay time.Duration,
) <-chan bool {
pStream := make(chan bool)
btnV := [2]bool{false, false}
go func() {
defer close(pStream)
for {
v1 := !pin.Get()
btnV[0] = v1
select {
case <-done:
return
case pStream <- btnV[0] && btnV[1]:
}
time.Sleep(time.Duration(delay) * time.Millisecond)
btnV[1] = btnV[0]
}
}()
return pStream
}
func readLightSensor(
done <-chan interface{},
delay time.Duration,
) <-chan uint16 {
sensor := machine.ADC{Pin: machine.WIO_LIGHT}
sensor.Configure(machine.ADCConfig{})
pStream := make(chan uint16)
go func() {
defer close(pStream)
for {
val := sensor.Get()
select {
case <-done:
return
case pStream <- val:
}
time.Sleep(time.Duration(delay) * time.Millisecond)
}
}()
return pStream
}
func lowPass(
done <-chan interface{},
vStream <-chan uint16,
) <-chan uint16 {
iStream := make(chan uint16)
his := uint16(0)
fir := func(val uint16) uint16 {
his = (his * 9 / 10) + (val * 1 / 10)
return his
}
go func() {
defer close(iStream)
for v := range vStream {
select {
case <-done:
return
case iStream <- fir(v):
}
}
}()
return iStream
}
Use Goroutine is so easy to compose different IO.
Latter will add a state machine use goroutine.
Comments