Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Nov 5, 2025. It is now read-only.
/gpioPublic archive

A native Go library for Raspberry Pi GPIO

License

NotificationsYou must be signed in to change notification settings

warthog618/gpio

Repository files navigation

Build StatusGoDocGo Report CardLicense: MIT

GPIO library for the Raspberry Pi.

gpio is a Go library for accessingGPIO pins on theRaspberryPi.

The library was inspired by and borrows fromgo-rpio, which is fast but lacksinterrupt support, andembd, which supportsinterrupts, but uses sysfs for read/write and has a far broader scope than Irequire.

This library does not support the Pi5, and never will.

⚠️ Deprecation Warning⚠️

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

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

There are a couple of downsides to switching togpiocdev:

  • The API is quite different, mostly due to the differences in the underlyingAPIs, so it is not a plugin replacement - you will need to do some coderework.
  • It is also slightly slower for both read and write as all hardware access isnow via kernel calls rather than via hardware registers. However, if that isan issue for you then you probably should be writing a kernel device driverfor your use case rather than trying to do something in userspace.
  • It requires a recent Linux kernel for full functionality. While the GPIOcharacter device has been around since v4.8, the bias and reconfigurationcapabilities required to provide functional equivalence togpio were onlyadded in v5.5.

There are several benefits in the switch:

  • gpiocdev is not Raspberry Pi specific, but will work on any platform wherethe GPIO chip is supported by the Linux kernel, so code usinggpiocdev ismore portable.
  • gpio writes directly to hardware registers so it can conflict with otherkernel drivers. Thegpiocdev accesses the hardware internally using the sameinterfaces as other kernel drivers and so should play nice with them.
  • gpiocdev 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 usinggpio togpiocdev andstrongly 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"github.com/warthog618/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 theNewPin function. The Pin object is thenused for all operations on that pin. Note that the pin number refers to the BCMGPIO pin, not the physical pin on the Raspberry Pi header. Pin 4 here is exposedon the pin header as physical pin 7 (J8 7). Mappings are provided from RaspberryPi 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 hasWatches set in which case you should remove theWatch.

Mode

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

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

To prevent output glitches, the pin level can be set usingHigh/Low/Writebefore the pin is set to Output.

Input

res:=pin.Read()// Read state from pin (High / Low)

Output

pin.High()// Set pin Highpin.Low()// Set pin Lowpin.Toggle()// Toggle pin (Low -> High -> Low)pin.Write(gpio.High)// Alternate syntax

Also see exampleexample/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 noPull 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.

funchandler(*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 theUnwatch function.

pin.Unwatch()

Tools

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

$ ./gppiiogppiio is a utility to control Raspberry Pi GPIO pinsUsage:  gppiio [flags]  gppiio [command]Available Commands:  detect      Identify the GPIO chip  get         Read the level of a pin or pinshelp        Help about anycommand  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 pinsset         Set the level of a pin or pins  version     Display the versionFlags:  -h, --helphelpfor gppiioUse"gppiio [command] --help"for more information about a command.

Examples

Refer to theexamples 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 andwith pins 15 and 16 tied together, possibly using a jumper across the header.The tests set J8 pin 16 to an output soDO NOT run them on hardware wherethat 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 Pivariants, 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 gotest -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: linuxgoarch: armpkg: github.com/warthog618/gpioBenchmarkRead                  9485052           124 ns/opBenchmarkWrite                18478959          58.8 ns/opBenchmarkToggle               16695492          72.4 ns/opBenchmarkInterruptLatency         2348        453248 ns/opBenchmarkSysfsRead               32983         31004 ns/opBenchmarkSysfsWrite              17192         69840 ns/opBenchmarkSysfsToggle             17341         62962 ns/opPASS

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 Pi4B. Note that the Raspberry Pi Model B Rev 1.0 has different pinouts, so the J8mappings 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 toinput pin values. The sysfs is not used to access the pin values, as thegpiomem approach is orders of magnitude faster (refer to the benchmarks).

About

A native Go library for Raspberry Pi GPIO

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp