forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
digital_pin.go
95 lines (79 loc) · 1.76 KB
/
digital_pin.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
package beaglebone
import (
"os"
"strconv"
)
type digitalPin struct {
PinNum string
Mode string
PinFile *os.File
Status string
}
const GPIOPath = "/sys/class/gpio"
const GPIODirectionRead = "in"
const GPIODirectionWrite = "out"
const HIGH = 1
const LOW = 0
func newDigitalPin(pinNum int, mode string) *digitalPin {
d := new(digitalPin)
d.PinNum = strconv.Itoa(pinNum)
fi, err := os.OpenFile(GPIOPath+"/export", os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
defer fi.Close()
fi.WriteString(d.PinNum)
d.setMode(mode)
return d
}
func (d *digitalPin) setMode(mode string) {
d.Mode = mode
if mode == "w" {
fi, err := os.OpenFile(GPIOPath+"/gpio"+d.PinNum+"/direction", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
fi.WriteString(GPIODirectionWrite)
fi.Close()
d.PinFile, err = os.OpenFile(GPIOPath+"/gpio"+d.PinNum+"/value", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
} else if mode == "r" {
fi, err := os.OpenFile(GPIOPath+"/gpio"+d.PinNum+"/direction", os.O_WRONLY, 0666)
if err != nil {
panic(err)
}
fi.WriteString(GPIODirectionRead)
fi.Close()
d.PinFile, err = os.OpenFile(GPIOPath+"/gpio"+d.PinNum+"/value", os.O_RDONLY, 0666)
if err != nil {
panic(err)
}
}
}
func (d *digitalPin) digitalWrite(value string) {
if d.Mode != "w" {
d.setMode("w")
}
d.PinFile.WriteString(value)
d.PinFile.Sync()
}
func (d *digitalPin) digitalRead() int {
if d.Mode != "r" {
d.setMode("r")
}
var buf []byte = make([]byte, 1)
d.PinFile.ReadAt(buf, 0)
i, _ := strconv.Atoi(string(buf[0]))
return i
}
func (d *digitalPin) close() {
fi, err := os.OpenFile(GPIOPath+"/unexport", os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
fi.WriteString(d.PinNum)
fi.Close()
d.PinFile.Close()
}