• Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
HomepcDuinoUse Go lang to control GPIO on pcDuino
Previous Next

Use Go lang to control GPIO on pcDuino

Posted by: admin , January 11, 2015

In this post, we show how to use Go lang to control GPIO on pcDuino.

If you have updated the image, sometimes, GPIO is not loaded by default. We need to use commands to load GPIO:

$sudo modprobe gpio
$sudo modprobe adc
$sudo modprobe pwm

The main program is as follows:

package main

import (
	"fmt"
	"./gpio"
	"time"
)

func main() {

	g, err := gpio.NewGPIOLine(7,gpio.OUT)
	if err != nil {
		fmt.Printf("Error setting up GPIO %v: %v", 18, err)
		return
	}

      blink(g, 100)
      g.Close()
}

func blink(g *gpio.GPIOLine, n uint) {
	fmt.Printf("blinking %v time(s)n", n)
	for i := uint(0); i < n; i++ {
		g.SetState(true)
		time.Sleep(time.Duration(1000) * time.Millisecond)
		g.SetState(false)
		time.Sleep(time.Duration(1000) * time.Millisecond)
	}
}

The package used is shown below:

package gpio

import (
	"fmt"
	"os"
)

type GPIOLine struct {
	Number uint
	fd     *os.File
}

const (
	IN = iota
	OUT
)

func NewGPIOLine(number uint, direction int) (gpio *GPIOLine, err error) {
	gpio = new(GPIOLine)
	gpio.Number = number

        err = gpio.SetDirection(direction)

	gpio.fd, err = os.OpenFile(fmt.Sprintf("/sys/devices/virtual/misc/gpio/pin/gpio%d", gpio.Number), os.O_WRONLY|os.O_SYNC, 0666)
	if err != nil {
		return nil, err
	}
	return gpio, nil
}

func (gpio *GPIOLine) SetDirection(direction int) error {
	df, err := os.OpenFile(fmt.Sprintf("/sys/devices/virtual/misc/gpio/mode/gpio%d", gpio.Number), os.O_WRONLY|os.O_SYNC, 0666)
	if err != nil {
		return err
	}
	fmt.Fprintln(df, "out")
	df.Close()
	return nil
}

func (gpio *GPIOLine) SetState(state bool) error {
	v := "0"
	if state {
		v = "1"
	}
	_, err := fmt.Fprintln(gpio.fd, v)
	return err
}

func (gpio *GPIOLine) Close() {
	gpio.fd.Close()
}

The code can be downloaded from pcduinogo.tar

Please download the above code to “$HOME/mygo”. To run the code, we do “$go run blink.go”.

IMG_2574

Share!
Tweet

admin

About the author

Leave a Reply Cancel reply

You must be logged in to post a comment.

Category

  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors