gpio

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2021 License: MIT Imports: 9 Imported by: 0

README

gpio

Build Status GoDoc Go Report Card

GPIO library for the Raspberry Pi.

gpio is a Go library for accessing GPIO pins on the Raspberry Pi.

The library was inspired by and borrows from go-rpio, which is fast but lacks interrupt support, and embd, which supports interrupts, but uses sysfs for read/write and has a far broader scope than I require.

⚠ Deprecation Warning ⚠

This library relies on the sysfs GPIO interface which is deprecated in the Linux kernel and is due for removal during 2020. Without sysfs, the watch/interrupt features of this library will no longer work.

The sysfs GPIO interface has been superceded in the Linux kernel by the GPIO character device. The newer API is sufficiently different that reworking this library to use that API is not practical. Instead I have written a new library, gpiod, that provides the same functionality as this library but using the GPIO character device.

There are a couple of downsides to switching to gpiod:

  • The API is quite different, mostly due to the differences in the underlying APIs, so it is not a plugin replacement - you will need to do some code rework.
  • It is also slightly slower for both read and write as all hardware access is now via kernel calls rather than via hardware registers. However, if that is an issue for you then you probably should be writing a kernel device driver for your use case rather than trying to do something in userspace.
  • It requires a recent Linux kernel for full functionality. While the GPIO character device has been around since v4.8, the bias and reconfiguration capabilities required to provide functional equivalence to gpio were only added in v5.5.

There are several benefits in the switch:

  • gpiod is not Raspberry Pi specific, but will work on any platform where the GPIO chip is supported by the Linux kernel, so code using gpiod is more portable.
  • gpio writes directly to hardware registers so it can conflict with other kernel drivers. The gpiod accesses the hardware internally using the same interfaces as other kernel drivers and so should play nice with them.
  • gpiod supports Linux GPIO line labels, so you can find your line by name (assuming it has been named by device-tree).
  • and of course, it will continue to work beyond 2020.

I've already ported all my projects that were using gpio to gpiod and strongly suggest that you do the same.

Features

Supports the following functionality:

  • Pin Mode/Direction (Input / Output)
  • Write (High / Low)
  • Read (High / Low)
  • Pullups (Up / Down / None)
  • Watches/Interrupts (Rising/Falling/Both)

Usage

import "gitee.com/lhjw9810/gpio"
Library Initialization

Open memory range for GPIO access in /dev/gpiomem

err := gpio.Open()

Cleanup when done

gpio.Close()
Pin Initialization

A Pin object is constructed using the NewPin function. The Pin object is then used for all operations on that pin. Note that the pin number refers to the BCM GPIO pin, not the physical pin on the Raspberry Pi header. Pin 4 here is exposed on the pin header as physical pin 7 (J8 7). Mappings are provided from Raspberry Pi J8 header pin names to BCM GPIO numbers, using the form J8pX.

pin := gpio.NewPin(4)
pin := gpio.NewPin(gpio.J8p7) // Using Raspberry Pi J8 mapping.

There is no need to cleanup a pin if you no longer need to use it, unless it has Watches set in which case you should remove the Watch.

Mode

The pin mode controls whether the pin is an input or output. The existing mode can be read back.

mode := pin.Mode()
pin.Output()               // Set mode to Output
pin.Input()                // Set mode to Input
pin.SetMode(gpio.Output)   // Alternate syntax

To prevent output glitches, the pin level can be set using High/Low/Write before the pin is set to Output.

Input
res := pin.Read()  // Read state from pin (High / Low)
Output
pin.High()              // Set pin High
pin.Low()               // Set pin Low
pin.Toggle()            // Toggle pin (Low -> High -> Low)

pin.Write(gpio.High)    // Alternate syntax

Also see example example/blinker/blinker.go

Pullups

Pull up state can be set using:

pin.PullUp()
pin.PullDown()
pin.PullNone()

pin.SetPull(gpio.PullUp)  // Alternate syntax

Unlike the Mode, the pull up state cannot be read back from hardware, so there is no Pull function.

Watches

The state of an input pin can be watched and trigger calls to handler functions.

The watch can be on rising or falling edges, or both.

The handler function is passed the triggering pin.

func handler(*Pin) {
  // handle change in pin value
}
pin.Watch(gpio.EdgeFalling,handler)    // Call handler when pin changes from High to Low.

pin.Watch(gpio.EdgeRising,handler)     // Call handler when pin changes from Low to High.

pin.Watch(gpio.EdgeBoth,handler)       // Call handler when pin changes

A watch can be removed using the Unwatch function.

pin.Unwatch()

Tools

A command line utility, gppiio, is provided to allow manual and scripted control of GPIO pins:

$ ./gppiio
gppiio is a utility to control Raspberry Pi GPIO pins

Usage:
  gppiio [flags]
  gppiio [command]

Available Commands:
  detect      Identify the GPIO chip
  get         Read the level of a pin or pins
  help        Help about any command
  mode        Read the functional mode of a pin or pins
  mon         Monitor the level of a pin or pins
  pull        Set the pull direction of a pin or pins
  set         Set the level of a pin or pins
  version     Display the version

Flags:
  -h, --help      help for gppiio

Use "gppiio [command] --help" for more information about a command.

Examples

Refer to the examples for more examples of usage.

Examples can be cross-compiled from other platforms using

GOOS=linux GOARCH=arm GOARM=6 go build

Tests

The library is fully tested, other than some error cases that are difficult to test.

The tests are intended to be run on a Raspberry Pi with J8 pin 7 floating and with pins 15 and 16 tied together, possibly using a jumper across the header. The tests set J8 pin 16 to an output so DO NOT run them on hardware where that pin is being externally driven.

Tests have been run successfully on Raspberry Pi B (Rev 1 and Rev 2), B+, Pi2 B, Pi4 B, and Pi Zero W. The library should also work on other Raspberry Pi variants, I just don't have any available to test.

The tests can be cross-compiled from other platforms using

GOOS=linux GOARCH=arm GOARM=6 go test -c

Later Pis can also use ARM7 (GOARM=7).

Benchmarks

The tests include benchmarks on reads and writes. Reading pin levels through sysfs is provided for comparison.

These are the results from a Raspberry Pi Zero W built with Go 1.13:

$ ./gpio.test -test.bench=.*
goos: linux
goarch: arm
pkg: gitee.com/lhjw9810/gpio
BenchmarkRead                  9485052           124 ns/op
BenchmarkWrite                18478959          58.8 ns/op
BenchmarkToggle               16695492          72.4 ns/op
BenchmarkInterruptLatency         2348        453248 ns/op
BenchmarkSysfsRead               32983         31004 ns/op
BenchmarkSysfsWrite              17192         69840 ns/op
BenchmarkSysfsToggle             17341         62962 ns/op

PASS

Prerequisites

The library assumes Linux, and has been tested on Raspbian Jessie, Stretch and Buster.

The library targets all models of the Raspberry Pi, upt to and including the Pi 4B. Note that the Raspberry Pi Model B Rev 1.0 has different pinouts, so the J8 mappings are incorrect for that particular revision.

This library utilizes /dev/gpiomem, which must be available to the current user. This is generally available in recent Raspian releases.

The library also utilizes the sysfs GPIO to support interrupts on changes to input pin values. The sysfs is not used to access the pin values, as the gpiomem approach is orders of magnitude faster (refer to the benchmarks).

Documentation

Overview

Package gpio provides GPIO access on the Raspberry Pi (rev 2 and later).

Supports simple operations such as: - Pin mode/direction (input/output) - Pin write (high/low) - Pin read (high/low) - Pull up/down/off

The package intentionally does not support:

  • the obsoleted rev 1 PCB (no longer worth the effort)
  • active low (to prevent confusion this package reflects only the actual hardware levels)

Example of use:

gpio.Open()
defer gpio.Close()

pin := gpio.NewPin(gpio.J8p7)
pin.Low()
pin.Output()

for {
	pin.Toggle()
	time.Sleep(time.Second)
}

The library uses the raw BCM2835 pin numbers, not the ports as they are mapped on the J8 output pins for the Raspberry Pi. A mapping from J8 to BCM is provided for those wanting to use the J8 numbering.

See the spec for full details of the BCM2835 controller: http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf

Index

Constants

View Source
const (
	J8p27 = iota
	J8p28
	J8p3
	J8p5
	J8p7
	J8p29
	J8p31
	J8p26
	J8p24
	J8p21
	J8p19
	J8p23
	J8p32
	J8p33
	J8p8
	J8p10
	J8p36
	J8p11
	J8p12
	J8p35
	J8p38
	J8p40
	J8p15
	J8p16
	J8p18
	J8p22
	J8p37
	J8p13
	MaxGPIOPin
)

Convenience mapping from J8 pinouts to BCM pinouts.

View Source
const (
	GPIO2  = J8p3
	GPIO3  = J8p5
	GPIO4  = J8p7
	GPIO5  = J8p29
	GPIO6  = J8p31
	GPIO7  = J8p26
	GPIO8  = J8p24
	GPIO9  = J8p21
	GPIO10 = J8p19
	GPIO11 = J8p23
	GPIO12 = J8p32
	GPIO13 = J8p33
	GPIO14 = J8p8
	GPIO15 = J8p10
	GPIO16 = J8p36
	GPIO17 = J8p11
	GPIO18 = J8p12
	GPIO19 = J8p35
	GPIO20 = J8p38
	GPIO21 = J8p40
	GPIO22 = J8p15
	GPIO23 = J8p16
	GPIO24 = J8p18
	GPIO25 = J8p22
	GPIO26 = J8p37
	GPIO27 = J8p13
)

GPIO aliases to J8 pins

View Source
const (
	// MaxGPIOInterrupt is the maximum pin number.
	MaxGPIOInterrupt = MaxGPIOPin
)

Variables

View Source
var (
	// ErrTimeout indicates the operation could not be performed within the
	// expected time.
	ErrTimeout = errors.New("timeout")

	// ErrBusy indicates the operation is already active on the pin.
	ErrBusy = errors.New("pin already in use")
)
View Source
var (
	// ErrAlreadyOpen indicates the mem is already open.
	ErrAlreadyOpen = errors.New("already open")
)

Functions

func Close

func Close() error

Close removes the interrupt handlers and unmaps GPIO memory

func Open

func Open() (err error)

Open and memory map GPIO memory range from /dev/gpiomem . Some reflection magic is used to convert it to a unsafe []uint32 pointer

Types

type Chipset added in v1.0.1

type Chipset int

Chipset identifies the GPIO chip.

const (

	// BCM2835 indicates the chipset is BCM2825 or compatible.
	BCM2835 Chipset

	// BCM2711 indicates the chipset is BCM2711.
	BCM2711
)

func Chip added in v1.0.1

func Chip() Chipset

Chip identifies the chipset on the system.

This is not valid until Open has been called.

type Edge

type Edge string

Edge represents the change in Pin level that triggers an interrupt.

const (
	// EdgeNone indicates no level transitions will trigger an interrupt
	EdgeNone Edge = "none"

	// EdgeRising indicates an interrupt is triggered when the pin transitions from low to high.
	EdgeRising Edge = "rising"

	// EdgeFalling indicates an interrupt is triggered when the pin transitions from high to low.
	EdgeFalling Edge = "falling"

	// EdgeBoth indicates an interrupt is triggered when the pin changes level.
	EdgeBoth Edge = "both"
)

type Level

type Level bool

Level represents the high (true) or low (false) level of a Pin.

const (
	Low  Level = false
	High Level = true
)

Level of pin, High / Low

type Mode

type Mode int

Mode defines the IO mode of a Pin.

const (
	Input Mode = iota
	Output
	Alt5
	Alt4
	Alt0
	Alt1
	Alt2
	Alt3
)

Pin Mode, a pin can be set in Input or Output mode

type Pin

type Pin struct {
	// contains filtered or unexported fields
}

Pin represents a single GPIO pin.

func NewPin

func NewPin(pin int) *Pin

NewPin creates a new pin object. The pin number provided is the BCM GPIO number.

func (*Pin) High

func (pin *Pin) High()

High sets pin High.

func (*Pin) Input

func (pin *Pin) Input()

Input sets pin as Input.

func (*Pin) Low

func (pin *Pin) Low()

Low sets pin Low.

func (*Pin) Mode

func (pin *Pin) Mode() Mode

Mode returns the mode of the pin in the Function Select register.

func (*Pin) Output

func (pin *Pin) Output()

Output sets pin as Output.

func (*Pin) Pin added in v1.0.1

func (pin *Pin) Pin() int

Pin returns the pin number that this Pin represents.

func (*Pin) PullDown

func (pin *Pin) PullDown()

PullDown sets the pull state of the Pin to PullDown.

func (*Pin) PullNone

func (pin *Pin) PullNone()

PullNone disables pullup/down on pin, leaving it floating.

func (*Pin) PullUp

func (pin *Pin) PullUp()

PullUp sets the pull state of the pin to PullUp.

func (*Pin) Read

func (pin *Pin) Read() (level Level)

Read pin state (high/low)

func (*Pin) SetMode

func (pin *Pin) SetMode(mode Mode)

SetMode sets the pin Mode.

func (*Pin) SetPull

func (pin *Pin) SetPull(pull Pull)

SetPull sets the pull up/down mode for a Pin. Unlike the mode, the pull value cannot be read back from hardware and so must be remembered by the caller.

func (*Pin) Shadow

func (pin *Pin) Shadow() Level

Shadow returns the value of the last write to an output pin or the last read on an input pin.

func (*Pin) Toggle

func (pin *Pin) Toggle()

Toggle pin state

func (*Pin) Unwatch

func (p *Pin) Unwatch()

Unwatch removes any watch from the pin.

func (*Pin) Watch

func (p *Pin) Watch(edge Edge, handler func(*Pin)) error

Watch the pin for changes to level.

The handler is called immediately, to allow the handler to initialise its state with the current level, and then on the specified edges. The edge determines which edge to watch. There can only be one watcher on the pin at a time.

func (*Pin) Write

func (pin *Pin) Write(level Level)

Set pin state (high/low)

type Pull

type Pull int

Pull defines the pull up/down state of a Pin.

const (
	// Values match bcm pull field.
	PullNone Pull = iota
	PullDown
	PullUp
)

Pull Up / Down / Off

type Watcher

type Watcher struct {
	// Guards the following, and sysfs interactions.
	sync.Mutex
	// contains filtered or unexported fields
}

Watcher monitors the pins for level transitions that trigger interrupts.

func NewWatcher

func NewWatcher() *Watcher

NewWatcher creates a goroutine that watches Pins for transitions that trigger interrupts.

func (*Watcher) Close

func (w *Watcher) Close()

Close - His watch has ended.

func (*Watcher) RegisterPin

func (w *Watcher) RegisterPin(pin *Pin, edge Edge, handler func(*Pin)) (err error)

RegisterPin creates a watch on the given pin.

The pin can only be registered once. Subsequent registers, without an Unregister, will return an error.

func (*Watcher) UnregisterPin

func (w *Watcher) UnregisterPin(pin *Pin)

UnregisterPin removes any watch on the Pin.

Directories

Path Synopsis
cmd
example
spi
mcp3w0c
Package mcp3w0c provides device drivers for MCP3004/3008/3204/3208 SPI ADCs.
Package mcp3w0c provides device drivers for MCP3004/3008/3204/3208 SPI ADCs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL