-
Notifications
You must be signed in to change notification settings - Fork 0
/
limit_switch.go
92 lines (80 loc) · 1.56 KB
/
limit_switch.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
package main
import (
"time"
rpio "github.com/stianeikeland/go-rpio"
)
const (
switchInputReadFrequency time.Duration = 20 * time.Millisecond
)
type LimitSwitch struct {
pin rpio.Pin
}
func NewLimitSwitch(pin rpio.Pin) *LimitSwitch {
s := &LimitSwitch{
pin: pin,
}
return s
}
func (s *LimitSwitch) Notify() <-chan bool {
notifyChan := make(chan bool, 1)
s.pin.PullUp()
go func() {
defer s.pin.PullOff()
switchInputTicker := time.NewTicker(switchInputReadFrequency)
isSwitchReleased := false
for {
select {
case <-switchInputTicker.C:
// First make sure the switch is in released position.
if !isSwitchReleased {
if s.pin.Read() == rpio.High {
isSwitchReleased = true
}
continue
}
// Now check if the switch was depressed.
if s.pin.Read() != rpio.Low {
continue
}
switchInputTicker.Stop()
notifyChan <- true
close(notifyChan)
return
}
}
}()
return notifyChan
}
/*
func (s *LimitSwitch) NotifyAfterRelease() <-chan bool {
notifyChan := make(chan bool, 1)
s.pin.PullUp()
go func() {
defer s.pin.PullOff()
switchInputTicker := time.NewTicker(switchInputReadFrequency)
valueToRead := rpio.Low
state := ""
for {
select {
case <-switchInputTicker.C:
val := s.pin.Read()
if val != valueToRead {
continue
}
valueToRead = rpio.High
if state == "" {
state = "pressed"
continue
}
if state == "pressed" {
switchInputTicker.Stop()
notifyChan <- true
//close(notifyChan)
return
}
}
}
}()
return notifyChan
}
*/