Detalhes do pacote

pigpio

fivdi2kMIT3.3.1

Fast GPIO, PWM, servo control, state change notification, and interrupt handling on the Raspberry Pi

gpio, pwm, servo, iot

readme (leia-me)

npm Version Downloads Per Month Mentioned in Awesome Node.js

pigpio

A wrapper for the pigpio C library to enable fast GPIO, PWM, servo control, state change notification and interrupt handling with Node.js on the Raspberry Pi Zero, 1, 2, 3 or 4.

pigpio supports Node.js versions 10, 12, 14, 15 and 16.

Contents

Features

  • Digital IO
    • Up to 3.5 million digital reads per second *)
    • Up to 2.5 million digital writes per second *)
  • PWM on any of GPIOs 0 through 31
    • Multiple frequencies and duty cycle ranges supported
  • Servo control on any of GPIOs 0 through 31
    • Jitter free
  • Alerts when any of GPIOs 0 through 31 change state
    • The time of the state change is available accurate to a few microseconds
  • Notification streams for monitoring state changes on any of GPIOs 0 through 31 concurrently
    • The time of the state changes are available accurate to a few microseconds
  • Low latency interrupt handlers
    • Handle up to 20000 interrupts per second *)
  • Read or write up to 32 GPIOs as one operation with banked GPIO
  • Trigger pulse generation
  • Pull up/down resistor configuration
  • Waveforms to generate GPIO level changes (time accurate to a few µs)

*) On a Raspberry Pi 4 Model B running Raspberry Pi OS 2021-03-04 (Buster 10.8) with pigpio v3.3.1, Node.js v16.0.0 and V79 of the pigpio C library.

Installation

Step 1 - Install the pigpio C library

The pigpio C library is a prerequisite for the pigpio Node.js module.

Run the following command to determine which version of the pigpio C library is installed:

pigpiod -v

For the Raspberry Pi Zero, 1, 2 and 3 V41 or higher of the pigpio C library is required. For the Raspberry Pi 4 V69 or higher is required.

If the pigpio C library is not installed or if the installed version is too old, the latest version can be installed with the following commands:

sudo apt-get update
sudo apt-get install pigpio

Alternative installation instructions for the pigpio C library can be found here.

Warning: The pigpio C library contains a number of utilities. One of these utilities is pigpiod which launches the pigpio C library as a daemon. This utility should not be used as the pigpio Node.js package uses the C library directly.

Step 2 - Install the pigpio Node.js package

npm install pigpio

Usage

Assume there's an LED connected to GPIO17 (pin 11) and a momentary push button connected to GPIO4 (pin 7).

Pulse an LED with PWM

Use PWM to pulse the LED connected to GPIO17 from fully off to fully on continuously.

const Gpio = require('pigpio').Gpio;

const led = new Gpio(17, {mode: Gpio.OUTPUT});

let dutyCycle = 0;

setInterval(() => {
  led.pwmWrite(dutyCycle);

  dutyCycle += 5;
  if (dutyCycle > 255) {
    dutyCycle = 0;
  }
}, 20);

Buttons and Interrupt Handling

Turn the LED connected to GPIO17 on when the momentary push button connected to GPIO4 is pressed. Turn the LED off when the button is released.

const Gpio = require('pigpio').Gpio;

const led = new Gpio(17, {mode: Gpio.OUTPUT});
const button = new Gpio(4, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_DOWN,
  edge: Gpio.EITHER_EDGE
});

button.on('interrupt', (level) => {
  led.digitalWrite(level);
});

Servo Control

Continuously move a servo connected to GPIO10 clockwise and anti-clockwise.

const Gpio = require('pigpio').Gpio;

const motor = new Gpio(10, {mode: Gpio.OUTPUT});

let pulseWidth = 1000;
let increment = 100;

setInterval(() => {
  motor.servoWrite(pulseWidth);

  pulseWidth += increment;
  if (pulseWidth >= 2000) {
    increment = -100;
  } else if (pulseWidth <= 1000) {
    increment = 100;
  }
}, 1000);

Measure Distance with a HC-SR04 Ultrasonic Sensor

The trigger function can be used to generate a pulse on a GPIO and alerts can be used to determine the time of a GPIO state change accurate to a few microseconds. These two features can be combined to measure distance using a HC-SR04 ultrasonic sensor.

const Gpio = require('pigpio').Gpio;

// The number of microseconds it takes sound to travel 1cm at 20 degrees celcius
const MICROSECDONDS_PER_CM = 1e6/34321;

const trigger = new Gpio(23, {mode: Gpio.OUTPUT});
const echo = new Gpio(24, {mode: Gpio.INPUT, alert: true});

trigger.digitalWrite(0); // Make sure trigger is low

const watchHCSR04 = () => {
  let startTick;

  echo.on('alert', (level, tick) => {
    if (level == 1) {
      startTick = tick;
    } else {
      const endTick = tick;
      const diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
      console.log(diff / 2 / MICROSECDONDS_PER_CM);
    }
  });
};

watchHCSR04();

// Trigger a distance measurement once per second
setInterval(() => {
  trigger.trigger(10, 1); // Set trigger high for 10 microseconds
}, 1000);

Determine the Width of a Pulse with Alerts

Alerts can be used to determine the time of a GPIO state change accurate to a few microseconds. Typically, alerts will be used for GPIO inputs but they can also be used for outputs. In this example, the trigger method is used to pulse the LED connected to GPIO17 on for 15 microseconds once per second. Alerts are used to measure the length of the pulse.

// Assumption: the LED is off when the program is started

const Gpio = require('pigpio').Gpio;

const led = new Gpio(17, {
  mode: Gpio.OUTPUT,
  alert: true
});

const watchLed = () => {
  let startTick;

  // Use alerts to determine how long the LED was turned on
  led.on('alert', (level, tick) => {
    if (level == 1) {
      startTick = tick;
    } else {
      const endTick = tick;
      const diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
      console.log(diff);
    }
  });
};

watchLed();

// Turn the LED on for 15 microseconds once per second
setInterval(() => {
  led.trigger(15, 1);
}, 1000);

Here's an example of the typical output to the console:

15
15
15
15
15
15
20
15
15
15
15

Debounce a Button

The GPIO glitch filter will prevent alert events from being emitted if the corresponding level change is not stable for at least a specified number of microseconds. This can be used to filter out unwanted noise from an input signal. In this example, a glitch filter is applied to filter out the contact bounce of a push button.

Button debounce circuit

const Gpio = require('pigpio').Gpio;

const button = new Gpio(23, {
  mode: Gpio.INPUT,
  pullUpDown: Gpio.PUD_UP,
  alert: true
});

let count = 0;

// Level must be stable for 10 ms before an alert event is emitted.
button.glitchFilter(10000);

button.on('alert', (level, tick) => {
  if (level === 0) {
    console.log(++count);
  }
});

Generate a waveform

Waveforms can be used to time and execute Gpio level changes with an accuracy up to 1 microsecond. The following example generates a waveform that starts with a 1µs pulse, then has a 2µs pause, followed by a 3µs pulse and so on. The waveform definition is a simple Array where each entry is an object with the properties gpioOn, gpioOff and usDelay.

The basic workflow to generate and execute waveforms is as follows:

First, we usually clear previous wave entries with the waveClear method. Then we can add pulses with the waveAddGeneric method to the cleared waveform. We then create a waveId by calling the waveCreate method. To execute the waveform, we call the waveTxSend method. Once the wave is sent, we can delete the wave by calling the waveDelete method.

const pigpio = require('pigpio');
const Gpio = pigpio.Gpio;

const outPin = 17;

const output = new Gpio(outPin, {mode: Gpio.OUTPUT});

output.digitalWrite(0);
pigpio.waveClear();

let waveform = [];

for (let x = 0; x < 20; x++) {
  if (x % 2 === 1) {
    waveform.push({ gpioOn: outPin, gpioOff: 0, usDelay: x + 1 });
  } else {
    waveform.push({ gpioOn: 0, gpioOff: outPin, usDelay: x + 1 });
  }
}

pigpio.waveAddGeneric(waveform);

let waveId = pigpio.waveCreate();

if (waveId >= 0) {
  pigpio.waveTxSend(waveId, pigpio.WAVE_MODE_ONE_SHOT);
}

while (pigpio.waveTxBusy()) {}

pigpio.waveDelete(waveId);

Sending a wavechain

The waveChain method allows you to chain multiple waveforms together. A chain is basically just an array with several waveId's. However you can insert different modifiers as described here.

In the example the chain consists of two waves. The first waveform is transmitted normally, then the second waveform is repeated 3 times.

const pigpio = require('pigpio');
const Gpio = pigpio.Gpio;

const outPin = 17;
const output = new Gpio(outPin, {mode: Gpio.OUTPUT});

output.digitalWrite(0);
pigpio.waveClear();

let firstWaveForm = [];
let secondWaveForm = [];

for (let x = 0; x < 10; x++) {
  if (x % 2 === 0) {
    firstWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 10 });
  } else {
    firstWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 10 });
  }
}

pigpio.waveAddGeneric(firstWaveForm);
let firstWaveId = pigpio.waveCreate();

for (let x = 0; x < 10; x++) {
  if (x % 2 === 0) {
    secondWaveForm.push({ gpioOn: outPin, gpioOff: 0, usDelay: 20 });
  } else {
    secondWaveForm.push({ gpioOn: 0, gpioOff: outPin, usDelay: 20 });
  }
}

pigpio.waveAddGeneric(secondWaveForm);
let secondWaveId = pigpio.waveCreate();

if (firstWaveId >= 0 && secondWaveId >= 0) {
  let chain = [firstWaveId, 255, 0, secondWaveId, 255, 1, 3, 0];
  pigpio.waveChain(chain);
}

while (pigpio.waveTxBusy()) {}

pigpio.waveDelete(firstWaveId);
pigpio.waveDelete(secondWaveId);

API Documentation

Classes

  • Gpio - General Purpose Input Output
  • GpioBank - Banked General Purpose Input Output
  • Notifier - Notification Stream

pigpio Module

Configuring pigpio

Limitations

  • The pigpio Node.js package is a wrapper for the pigpio C library. A limitation of the pigpio C library is that it can only be used by a single running process.
  • The pigpio C library and therefore the pigpio Node.js package requires root/sudo privileges to access hardware peripherals.

Troubleshooting

If you have a problem with the library, before you remove it from your code and start trying something else, please check the troubleshooting page first. Some problems are solvable and documented.

Related Packages

Here are a few links to other hardware specific Node.js packages that may be of interest.

  • onoff - GPIO access and interrupt detection
  • i2c-bus - I2C serial bus access
  • spi-device - SPI serial bus access
  • mcp-spi-adc - Analog to digital conversion with the MCP3002/4/8, MCP3202/4/8 and MCP3304
  • pigpio-dht - Implements logic to read DHT11 or DHT22/AM2302 temperature and relative humidity sensor
  • pigpio-mock - A pigpio mock library for development on your local machine

changelog (log de mudanças)

3.3.1 / Apr 30 2021

  • raspberry pi 4 now officially supported
  • drop support for node 13 and add support for node 16

3.3.0 / Jan 06 2021

  • drop support for node 8 and add support for node 15
  • update dependencies, update .travis.yml
  • remove old news from news and updates section of readme

3.2.4 / Sep 26 2020

  • Fix "which" test in binding.gyp to support more platforms (#120)

3.2.3 / May 11 2020

  • describe the potential cause of a 'module did not self-register' error

3.2.2 / May 08 2020

  • improve exception handling (#111)

3.2.1 / May 02 2020

  • ensure that pigpio installs without errors on alpine linux systems (#109)

3.2.0 / May 02 2020

  • ensure that pigpio installs without errors on all linux systems
  • add travis build

3.1.1 / Apr 24 2020

  • update dependencies (nan v2.14.1, jshint v2.11.0)
  • document support for node 14

3.1.0 / Apr 08 2020

  • Adds type definitions for TypeScript (thank you @cinderblock)

3.0.0 / Jan 12 2020

2.0.1 / Sep 22 2019

  • drop support for node.js v4

2.0.0 / Sep 06 2019

  • suppress cast-function-type warnings
  • raspberry pi 4 support

1.3.0 / Sep 06 2019

1.2.3 / Jun 16 2019

  • update dependencies
  • update npm keywords

1.2.2 / Mar 16 2019

  • update dependencies (nan v2.13.1, bindings v1.5.0)
  • document node 12 support
  • lint with jshint
  • only compile c++ code on linux

1.2.1 / Dec 19 2018

  • update dependencies (nan v2.12.1, bindings v1.3.1)

1.2.0 / Nov 25 2018

  • add getTick and tickDiff (thank you @erikma)

1.1.4 / Oct 13 2018

1.1.3 / Sep 29 2018

  • update dependencies (nan v2.11.1)
  • adapt to V8 7.0: replace v8Value->Uint32Value() with Nan::To<uint32_t>(v8Value).FromJust()
  • adapt to V8 7.0: replace v8Value->Int32Value() with Nan::To<int32_t>(v8Value).FromJust()
  • adapting to V8 7.0 had a negative impact on performance

1.1.2 / Jul 27 2018

  • modernize codebase

1.1.1 / Jul 22 2018

  • add troubleshooting guide (thank you @sznowicki)
  • construct AsyncResource for callback when callback is stored

1.1.0 / May 20 2018

  • add Gpio.glitchFilter

1.0.0 / Apr 07 2018

  • document difference between interrupts and alerts
  • update dependencies (nan v2.10.0)

0.7.0 / Feb 25 2018

  • update dependencies (nan v2.9.2)
  • fix deprecations
  • drop support for node.js v0.10, v0.12, v5 and v7
  • use default pipe size for notifiers

0.6.4 / Dec 24 2017

  • don't suppress deprecated-declaration warnings
  • update dependencies

0.6.3 / Nov 04 2017

  • suppress deprecated-declaration warnings
  • document node 9 support

0.6.2 / Sep 18 2017

  • document necessity for root privileges
  • update dependencies (bindings@1.3.0, nan@2.7.0)
  • allow initialize to be called after terminate has been called #34

0.6.1 / Jul 15 2017

  • improve documentation

0.6.0 / Jun 10 2017

  • allow socket port number to be configured with configureSocketPort

0.5.1 / Apr 13 2017

  • fix test script

0.5.0 / Apr 13 2017

  • hardwareRevision API
  • nan v2.6.2

0.4.0 / Sep 24 2016

  • example: measure distance with a HC-SR04 ultrasonic sensor
  • initialize and terminate added to public API
  • nan v2.4.0
  • document initialize and terminate

0.3.4 / May 15 2016

  • installation instructions updated

0.3.3 / May 04 2016

  • nan v2.3.2

0.3.2 / Feb 21 2016

  • notifier-leak-check now functions correctly
  • notifier example

0.3.1 / Feb 21 2016

  • document notification streams
  • documentation tweaks
  • notifier-leak-check added

0.3.0 / Feb 14 2016

  • upgrade to nan v2.2.0
  • alerts

0.2.0 / Dec 13 2015

  • trigger pulse generation
  • banked gpio

0.1.3 / Dec 05 2015

  • prevent Nan::ErrnoException related segmentation faults in v0.10.29

0.1.2 / Dec 05 2015

  • include errno.h for node v0.10.29

0.1.1 / Nov 28 2015

  • document dependency on V41 or higher of the pigpio C library

0.1.0 / Nov 28 2015

  • export Gpio constructor as exports.Gpio
  • high precision notifications with Notifier
  • hardware pwm support
  • renamed analogWrite to pwmWrite
  • clock configuration with configureClock
  • notification pipe size set to 1048576
  • notification stress test

0.0.8 / Nov 08 2015

  • allow PWM range control with pwmRange, getPwmRange, getPwmRealRange
  • allow pwm frequency control with pwmFrequency, and getPwmFrequency
  • pwm tests
  • pinMode renamed to mode
  • getPinMode renamed to getMode

0.0.7 / Nov 03 2015

  • fixed version in package.json (v0.0.5 -> v0.0.7)
  • v0.0.6 was never published on npm

0.0.6 / Nov 03 2015

  • constants MIN_GPIO, MAX_GPIO, and MAX_USER_GPIO added
  • mode tests
  • multiple interrupt sources test
  • allow access to PWM duty cycle with getPwmDutyCycle
  • allow access to servo pulse width with getServoPulseWidth
  • servo control test

0.0.5 / Nov 03 2015

  • documentation improved
  • tick argument for interrupt event removed
  • fixed getPinMode bug
  • gpio-info example

0.0.4 / Nov 02 2015

  • documentation, tests, and examples improved
  • gpio argument for interrupt event removed
  • simple servo example

0.0.3 / Nov 01 2015

  • enableInterrupt timeout argument made optional
  • interrupt timeout integration tests

0.0.2 / Nov 01 2015

  • integration tests
  • documentation

0.0.1 / Oct 31 2015

  • interrupt support with gpioSetISRFunc
  • throw errors when pigpio c interface returns errors
  • export Gpio constructor rather than pigpio c interface
  • simple examples

0.0.0 / Oct 14 2015

  • minimalistic pigpio api