-
Notifications
You must be signed in to change notification settings - Fork 0
/
blinker.go
96 lines (84 loc) · 1.73 KB
/
blinker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"fmt"
"sync"
"time"
rpio "github.com/stianeikeland/go-rpio"
)
const blinkerPin = 10
type BlinkSpeed int
const (
BlinkFastest BlinkSpeed = iota
BlinkFast
BlinkNormal
BlinkSlow
BlinkSlowest
)
func (blinkSpeed BlinkSpeed) Duration() time.Duration {
return map[BlinkSpeed]time.Duration{
BlinkFastest: 50 * time.Millisecond,
BlinkFast: 100 * time.Millisecond,
BlinkNormal: 500 * time.Millisecond,
BlinkSlow: 700 * time.Millisecond,
BlinkSlowest: 1500 * time.Millisecond,
}[blinkSpeed]
}
type Blinker struct {
pin rpio.Pin
onDuration time.Duration
offDuration time.Duration
stopChan chan bool
toggle chan bool
wg sync.WaitGroup
}
func NewBlinker(pin int, speed BlinkSpeed) *Blinker {
rpioPin := rpio.Pin(pin)
rpioPin.Output()
return &Blinker{
pin: rpioPin,
onDuration: speed.Duration(),
offDuration: speed.Duration(),
toggle: make(chan bool),
}
}
func (blinker *Blinker) Blink() {
blinker.stopChan = make(chan bool)
// ON
go func() {
for {
select {
case <-blinker.stopChan:
fmt.Println("Stop signal received. [ON]")
return
case <-blinker.toggle:
//fmt.Println("ON")
blinker.pin.High()
time.Sleep(blinker.onDuration)
blinker.toggle <- true
}
}
}()
// OFF
go func() {
for {
select {
case <-blinker.stopChan:
fmt.Println("Stop signal received. [OFF]")
return
case <-blinker.toggle:
//fmt.Println("OFF")
blinker.pin.Low()
time.Sleep(blinker.offDuration)
blinker.toggle <- true
}
}
}()
//kick off the blinking.
blinker.toggle <- true
}
func (blinker *Blinker) Stop() {
fmt.Println("Stopping the blinker")
close(blinker.stopChan)
<-blinker.toggle
blinker.pin.Low()
}