forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
digital_pin.go
84 lines (71 loc) · 1.87 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
package sysfs
import (
"fmt"
"io/ioutil"
"os"
"strconv"
)
const (
IN = "in"
OUT = "out"
HIGH = 1
LOW = 0
GPIOPATH = "/sys/class/gpio"
)
type DigitalPin struct {
pin string
label string
direction string
}
// NewDigitalPin returns a DigitalPin given the pin number and sysfs pin label
func NewDigitalPin(pin int, v ...string) *DigitalPin {
d := &DigitalPin{pin: strconv.Itoa(pin)}
if len(v) > 0 {
d.label = v[0]
} else {
d.label = "gpio" + d.pin
}
return d
}
// Direction returns the current direction of the pin
func (d *DigitalPin) Direction() string {
return d.direction
}
// SetDirection sets the current direction for specified pin
func (d *DigitalPin) SetDirection(dir string) error {
d.direction = dir
_, err := writeFile(fmt.Sprintf("%v/%v/direction", GPIOPATH, d.label), []byte(d.direction))
return err
}
// Write writes specified value to the pin
func (d *DigitalPin) Write(b int) error {
_, err := writeFile(fmt.Sprintf("%v/%v/value", GPIOPATH, d.label), []byte(strconv.Itoa(b)))
return err
}
// Read reads the current value of the pin
func (d *DigitalPin) Read() (n int, err error) {
buf, err := ioutil.ReadFile(fmt.Sprintf("%v/%v/value", GPIOPATH, d.label))
if err != nil {
return
}
return strconv.Atoi(string(buf[0]))
}
// Export exports the pin for use by the operating system
func (d *DigitalPin) Export() error {
_, err := writeFile(GPIOPATH+"/export", []byte(d.pin))
return err
}
// Unexport unexports the pin and releases the pin from the operating system
func (d *DigitalPin) Unexport() error {
_, err := writeFile(GPIOPATH+"/unexport", []byte(d.pin))
return err
}
// writeFile validates file existence and writes data into it
func writeFile(name string, data []byte) (i int, err error) {
file, err := os.OpenFile(name, os.O_WRONLY, 0644)
defer file.Close()
if err != nil {
return
}
return file.Write(data)
}