hybridgroup.gobot/sysfs/digital_pin.go

85 lines
1.9 KiB
Go
Raw Normal View History

package sysfs
import (
"fmt"
"io/ioutil"
"os"
"strconv"
)
const (
2014-10-31 04:41:27 +08:00
IN = "in"
OUT = "out"
HIGH = 1
LOW = 0
GPIOPATH = "/sys/class/gpio"
)
type DigitalPin struct {
pin string
2014-10-31 04:41:27 +08:00
label string
direction string
}
2014-10-31 04:41:27 +08:00
// NewDigitalPin returns a DigitalPin given the pin number and sysfs pin label
2014-10-31 06:26:31 +08:00
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
}
2014-10-31 04:41:27 +08:00
// Direction returns the current direction of the pin
func (d *DigitalPin) Direction() string {
return d.direction
}
2014-10-31 04:41:27 +08:00
// SetDirection sets the current direction for specified pin
func (d *DigitalPin) SetDirection(dir string) error {
d.direction = dir
2014-10-31 04:41:27 +08:00
_, err := writeFile(fmt.Sprintf("%v/%v/direction", GPIOPATH, d.label), []byte(d.direction))
return err
}
2014-10-31 04:41:27 +08:00
// 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
}
2014-10-31 04:41:27 +08:00
// 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]))
}
2014-10-31 04:41:27 +08:00
// Export exports the pin for use by the operating system
func (d *DigitalPin) Export() error {
2014-10-31 04:41:27 +08:00
_, err := writeFile(GPIOPATH+"/export", []byte(d.pin))
return err
}
2014-10-31 04:41:27 +08:00
// Unexport unexports the pin and releases the pin from the operating system
func (d *DigitalPin) Unexport() error {
2014-10-31 04:41:27 +08:00
_, err := writeFile(GPIOPATH+"/unexport", []byte(d.pin))
return err
}
2014-10-31 04:41:27 +08:00
// 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)
}