Skip to content

Instantly share code, notes, and snippets.

@titpetric
Created July 19, 2016 14:45
Show Gist options
  • Save titpetric/bc3e43b2c6efc2cd9364cf52ffbc17c4 to your computer and use it in GitHub Desktop.
Save titpetric/bc3e43b2c6efc2cd9364cf52ffbc17c4 to your computer and use it in GitHub Desktop.
Using GPIO pins with GoLang
package main
import "os"
import "io/ioutil"
import "time"
type GPIO struct{}
func (r GPIO) Pin(name string) GPIO_Pin {
pin := GPIO_Pin{name}
filename := pin.Filename()
if _, err := os.Stat(filename); os.IsNotExist(err) {
// export gpio pin
ioutil.WriteFile("/sys/class/gpio/export", []byte(pin.Name), 0666)
}
return pin
}
type GPIO_Pin struct {
Name string
}
func (r GPIO_Pin) Filename() string {
return "/sys/class/gpio/gpio" + r.Name
}
func (r GPIO_Pin) write(where, what string) GPIO_Pin {
filename := r.Filename() + "/" + where
ioutil.WriteFile(filename, []byte(what), 0666)
return r
}
func (r GPIO_Pin) Output() GPIO_Pin {
return r.write("direction", "out")
}
func (r GPIO_Pin) Input() GPIO_Pin {
return r.write("direction", "in")
}
func (r GPIO_Pin) High() GPIO_Pin {
return r.write("value", "1")
}
func (r GPIO_Pin) Low() GPIO_Pin {
return r.write("value", "0")
}
func main() {
pins1 := []string{"26", "19", "13", "6"}
pins2 := []string{"24", "23", "18", "25", "12", "16", "21", "20"}
i := 0
gpio := GPIO{}
for i < 1600 {
i1 := (i) % len(pins1)
gpio.Pin(pins1[i1]).Output().Low()
i2 := (i) % len(pins2)
gpio.Pin(pins2[i2]).Output().Low()
i3 := (i + 4) % len(pins2)
gpio.Pin(pins2[i3]).Output().Low()
time.Sleep(200 * time.Millisecond)
gpio.Pin(pins1[i1]).High()
gpio.Pin(pins2[i2]).High()
gpio.Pin(pins2[i3]).High()
i++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment