Git Product home page Git Product logo

pigpio's Introduction

Build Status 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

pigpio's People

Contributors

7aman avatar adipascu avatar cinderblock avatar dvdberg avatar erikmav avatar fivdi avatar joeferner avatar schoero avatar sznowicki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pigpio's Issues

node-gyp build fails

Built pigpio(d) version 64 successfully and it passes all the tests provided.

But installing js pigpio throws all kind of nan errors.
using node 7.10, npm 4.2, gcc 5.4, ubuntu mate 16.04 on a RPI3

In file included from ../../nan/nan.h:194:0,
                 from ../src/pigpio.cc:2:
../../nan/nan_maybe_43_inl.h: In function ‘Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array>, uint32_t)’:
../../nan/nan_maybe_43_inl.h:221:58: warning: ‘v8::MaybeLocal<v8::Object> v8::Array::CloneElementAt(v8::Local<v8::Context>, uint32_t)’ is deprecated: Cloning is not supported. [-Wdeprecated-declarations]
   return array->CloneElementAt(GetCurrentContext(), index);
                                                          ^
In file included from /home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:26:0,
                 from /home/sysadmin/.node-gyp/7.10.0/include/node/node.h:42,
                 from ../../nan/nan.h:45,
                 from ../src/pigpio.cc:2:
/home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:3347:36: note: declared here
                 MaybeLocal<Object> CloneElementAt(Local<Context> context,
                                    ^
/home/sysadmin/.node-gyp/7.10.0/include/node/v8config.h:329:3: note: in definition of macro ‘V8_DEPRECATED’
   declarator __attribute__((deprecated(message)))
   ^
In file included from ../../nan/nan_new.h:189:0,
                 from ../../nan/nan.h:200,
                 from ../src/pigpio.cc:2:
../../nan/nan_implementation_12_inl.h: In static member function ‘static Nan::imp::FactoryBase<v8::BooleanObject>::return_t Nan::imp::Factory<v8::BooleanObject>::New(bool)’:
../../nan/nan_implementation_12_inl.h:40:38: warning: ‘static v8::Local<v8::Value> v8::BooleanObject::New(bool)’ is deprecated: Pass an isolate [-Wdeprecated-declarations]
   return v8::BooleanObject::New(value).As<v8::BooleanObject>();
                                      ^
In file included from /home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:26:0,
                 from /home/sysadmin/.node-gyp/7.10.0/include/node/node.h:42,
                 from ../../nan/nan.h:45,
                 from ../src/pigpio.cc:2:
/home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:4490:56: note: declared here
   V8_DEPRECATED("Pass an isolate", static Local<Value> New(bool value));
                                                        ^
/home/sysadmin/.node-gyp/7.10.0/include/node/v8config.h:329:3: note: in definition of macro ‘V8_DEPRECATED’
   declarator __attribute__((deprecated(message)))
   ^
In file included from ../src/pigpio.cc:2:0:
../../nan/nan.h: At global scope:
../../nan/nan.h:602:20: error: variable or field ‘AddGCEpilogueCallback’ declared void
       v8::Isolate::GCEpilogueCallback callback
                    ^
../../nan/nan.h:602:7: error: ‘GCEpilogueCallback’ is not a member of ‘v8::Isolate’
       v8::Isolate::GCEpilogueCallback callback
       ^
../../nan/nan.h:603:18: error: expected primary-expression before ‘gc_type_filter’
     , v8::GCType gc_type_filter = v8::kGCTypeAll) {
                  ^
../../nan/nan.h:608:20: error: variable or field ‘RemoveGCEpilogueCallback’ declared void
       v8::Isolate::GCEpilogueCallback callback) {
                    ^
../../nan/nan.h:608:7: error: ‘GCEpilogueCallback’ is not a member of ‘v8::Isolate’
       v8::Isolate::GCEpilogueCallback callback) {
       ^
../../nan/nan.h:613:20: error: variable or field ‘AddGCPrologueCallback’ declared void
       v8::Isolate::GCPrologueCallback callback
                    ^
../../nan/nan.h:613:7: error: ‘GCPrologueCallback’ is not a member of ‘v8::Isolate’
       v8::Isolate::GCPrologueCallback callback
       ^
../../nan/nan.h:614:18: error: expected primary-expression before ‘gc_type_filter’
     , v8::GCType gc_type_filter = v8::kGCTypeAll) {
                  ^
../../nan/nan.h:619:20: error: variable or field ‘RemoveGCPrologueCallback’ declared void
       v8::Isolate::GCPrologueCallback callback) {
                    ^
../../nan/nan.h:619:7: error: ‘GCPrologueCallback’ is not a member of ‘v8::Isolate’
       v8::Isolate::GCPrologueCallback callback) {
       ^
../../nan/nan.h: In function ‘bool Nan::SetAccessor(v8::Local<v8::Object>, v8::Local<v8::String>, Nan::GetterCallback, Nan::SetterCallback, v8::Local<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’:
../../nan/nan.h:1961:16: warning: ‘bool v8::Object::SetAccessor(v8::Local<v8::Name>, v8::AccessorNameGetterCallback, v8::AccessorNameSetterCallback, v8::Local<v8::Value>, v8::AccessControl, v8::PropertyAttribute)’ is deprecated: Use maybe version [-Wdeprecated-declarations]
     , attribute);
                ^
In file included from /home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:26:0,
                 from /home/sysadmin/.node-gyp/7.10.0/include/node/node.h:42,
                 from ../../nan/nan.h:45,
                 from ../src/pigpio.cc:2:
/home/sysadmin/.node-gyp/7.10.0/include/node/v8.h:3027:22: note: declared here
                 bool SetAccessor(Local<Name> name,
                      ^
/home/sysadmin/.node-gyp/7.10.0/include/node/v8config.h:329:3: note: in definition of macro ‘V8_DEPRECATED’
   declarator __attribute__((deprecated(message)))
   ^
pigpio.target.mk:94: recipe for target 'Release/obj.target/pigpio/src/pigpio.o' failed
make: *** [Release/obj.target/pigpio/src/pigpio.o] Error 1
make: Leaving directory '/home/sysadmin/uci/uci-examples/node_modules/uci-interrupt/node_modules/pigpio/build'

Calling PIGPIO from multiple task failed

I have two child processes, each one control specific PIN through pigpio.
when the second subtask starts, i obtain this error
2017-07-08 15:02:10 initInitialise: Can't lock /var/run/pigpio.pid
~/node_modules/pigpio/pigpio.js:11
pigpio.gpioInitialise();
^

Error: pigpio error -1 in gpioInitialise
at initializePigpio (/node_modules/pigpio/pigpio.js:11:12)
at new Gpio (
/node_modules/pigpio/pigpio.js:25:3)

Could be possible to use pigpio from multiple task at the moment?
Why this limitation? I miss something?

Signal Handler

Hai,
When i execute the program in loop and terminates it by pressing CTRL+C it gives me this signal handler

sigHandler: Unhandled signal 2, terminating

How to over come this

Sound stream breaks when initing the library

This is probably not a bug in the library but maybe someone here would help me understanding what's going on.

I have a small RPi monitoring server implementation that uses the pigpio library in order to control the Google Voice Kit button and LED light.

Repo is here: https://github.com/sznowicki/rpi-av-monitoring-server.

When the node process is starting, it starts the mjpeg (video) and darkice (audio) stream.

At the moment I init the pigpio, audio stream goes mad. The full implementation is here, but in order to narrow the possible suspects i did a following test:

  1. Start audio stream (darkice app, streams mp3 from alsa plug:micboost
  2. Check if works -> works fine, no problems.
  3. Open node project, import lib and init one device:
const Gpio = require('pigpio').Gpio; // all good
const l = new Gpio(25, { mode: Gpio.OUTPUT }); 
  1. At the moment const l = new Gpio(25, { mode: Gpio.OUTPUT }); is called, darkice goes crazy throwing this warning repeatedly AlsaDspSource :: Buffer overrun!

It's broken even if I kill node and darkice. As long as the device is not rebooted, the Buffer overrun is always thrown.


I suspect that maybe, the library is abusing the connection on GPIO bus and makes "everything" too busy so the Google Voice Kit hat is not able to process audio any more?

Can it be the problem?

If not, I'd be glad for any suggestions how to deal with this issue.

GPIO Cleanup

Hai,
Can i know how to clean the GPIO using your library

Library ignores any nodejs signal handlers that were attached before it has initialized

#6

Consider this code sample borrowed from the issue referenced (a little change in the SIGINT handler):

var Gpio = require('pigpio').Gpio,
  led = new Gpio(17, {mode: Gpio.OUTPUT}),
  iv;

var iv = setInterval(function () {
  led.digitalWrite(led.digitalRead() ^ 1);
}, 1000);

process.on('SIGINT', function () {
  process.exit();
});

Now, if we were to put the SIGINT (or any other signal, as my tests showed) handler before the library module gets require()ed:

process.on('SIGINT', function () {
  process.exit();
});

var Gpio = require('pigpio').Gpio,
  led = new Gpio(17, {mode: Gpio.OUTPUT}),
  iv;

var iv = setInterval(function () {
  led.digitalWrite(led.digitalRead() ^ 1);
}, 1000);

Then we still get the sigHandler: Unhandled signal 2, terminating

It took me quite some time to debug this out throughout my code, because I've got a custom signal handler inside a seperate file, which is required in different files which attach more functions to it before it calls process.exit. And, the first time my signal handler is being require()ed (and doing process.on('SIGINT', ...)), is before the first time pigpio gets require()ed, just like the second code example I put, so perhaps the pigpio's initialization is doing something not properly.

This issue is more than just avoiding the sigHandler: Unhandled signal 2, terminating - the scenario I described, when is performed using, for instance, nodemon, caused some even more serious errors to be output.

Hope I made it clear enough,
Shtaif.

Script crash with error after rpi3 reboot.

This error is spinning in a loop after rpi reboot until manually stopping the forever.

/home/antio/smarthome/node_modules/bindings/bindings.js:83
        throw e
              ^
Error: /home/antio/smarthome/node_modules/pigpio/build/Release/pigpio.node: undefined symbol: node_module_register
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at bindings (/home/antio/smarthome/node_modules/bindings/bindings.js:76:44)
    at Object.<anonymous> (/home/antio/smarthome/node_modules/pigpio/pigpio.js:5:31)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
error: Forever detected script exited with code: 8
error: Script restart attempt #133

pigpio on docker image

Hello.

I'd like use your lib in a docker container inside raspberry pi.

Can you tell me what volumes I need map to container access rasp gpios?

Creating volumes, it works transparent for application.

Thanks

Waveforms

Great pigpio Node support but I miss the waveforms that the C and Python implementations allow.
Without them I do not see any easy way of generating serial signals.
I hope to see this addition soon.
Regards

Change name to avoid confusion?

Just a susggestion but maybe better to call this pigpioj or something like that. Calling it pigpio can cause confusion - at least it did for me when someone suggested using it on the Pi forum :)

How to enable low-level DEBUG messaging?

The pigpio library provides a logging facility: Is it possible to enable this at runtime?
Perhaps it requires some helper function to set the debug level at running, e.g. configureDebugLevel()

interrupt triggers on both edges when leading edge is configured

problem: a pin configure with {edge: Pgpio.LEADING_EDGE} still fires falling edge interrupts. Variations on the following code taken from documentation did not work.

const Gpio = require('pigpio').Gpio;
const testPin = new Gpio(26, {mode: Gpio.INPUT, pullUpDown: Gpio.PUD_DOWN, edge: Gpio.RISING_EDGE});
testPin.disableInterrupt(); # tried disabling and reenabling to no avail
console.log('interrupt value is', Gpio.RISING_EDGE); # do I actually set a value
testPin.enableInterrupt(Gpio.RISING_EDGE);
testPin.on('interrupt', function (level) {
  console.log(`we got an interrupt ${level}`); #get both edges no matter what
  setTimeout(() => {console.log('ok, after 3 seconds', testPin.digitalRead())}, 3000); # sanity check pin
});

Outputs:
interrupt value is 0
# Set Pin HIGH for ~ 1 second 
we got an interrupt 1
we got an interrupt 0
ok, after 3 seconds 0
ok, after 3 seconds 0

This problem existed for me in the C lib as well so may not be a bug in the binding code but if you tested this then perhaps I am doing something wrong which I'd love to discover so I can fix it.

Bit Banging Operations

Hello! Awesome work with this library. I'm wondering if you have plans or interest in supporting the bit banging operations capable with the pigpio c library?

Specifically, I'm interested in the TX associated functions

gpioWaveClear
gpioWaveAddNew
gpioWaveAddGeneric
gpioWaveAddSerial   
gpioWaveCreate  
gpioWaveDelete  
gpioWaveTxSend
gpioWaveTxBusy

and the RX associated functions

gpioSerialReadOpen
gpioSerialRead
gpioSerialReadClose

If you are not planning to add these, perhaps I could assist in integrating them?

"Sorry, you don't have permission to run this program."

2015-12-11 15:36:28 initCheckPermitted: 
+---------------------------------------------------------+
|Sorry, you don't have permission to run this program.    |
|Try running as root, e.g. precede the command with sudo. |
+---------------------------------------------------------+
Error: pigpio error -1 in gpioInitialise

Thrown in https://github.com/rpicopter/pigpio/blob/master/pigpio.c#L3697

Running my app as root using sudo throws other exceptions, so is there anything I can do to make the library run as a non-root user?

Notifiers and "ESPIPE: invalid seek, read" errors

Attempting to use Notifiers with Node v8.10.0 will result in the following error:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: ESPIPE: invalid seek, read

With Node v8.9.4 Notifiers work correctly and there are no errors.

Under the covers a Notifier is a named pipe created by the pigpio C library by calling mkfifo. On the JavaScript side a read stream is used to read notifications from the named pipe.

This appears to be related to nodejs/node#19240

Getting multiple events when button pressed

I am using a membrane button, one lead to ground, other to GPIO 12. Code below. Problem is that I occasionally get multiple events when I click the button...

var Gpio = require('pigpio').Gpio;
var button1 = new Gpio(12, {
    mode: Gpio.INPUT,
    pullUpDown: Gpio.PUD_UP,
    edge: Gpio.FALLING_EDGE
  });

button1.on('interrupt', function (level) {
        if (level === 0) {
                console.log("Button1 Pressed!");
        }
});

How to use terminate() function

Hi! Awesome code that you wrote! Thanks a lot for this work!

I'm trying to understand how to use the terminate() function.

Basically, my "hello world" code is the following one:

var led = new Gpio(5, {mode: Gpio.OUTPUT});

setInterval(function(err) {
  if (err) { throw err; }
  led.pwmWrite(127);
}, 200);

process.on('SIGINT', function() {
  led.terminate();
});

What I intend to do is to free the variables when I hit "Ctrl+C" on a linux terminal. When I do that, the led is still HIGH, and I have to run the program, hit Ctrl+C for the second time to turn the led off.

All the times that I hit Ctrl+C, I got this error:

led.terminate();
      ^

TypeError: led.terminate is not a function
    at process.<anonymous> (/home/pi/[repo name]/index.js:22:7)
    at emitNone (events.js:86:13)
    at process.emit (events.js:185:7)
    at Signal.wrap.onsignal (internal/process.js:199:44)

I'm doing it the right way? It's possible to free the variable (and return the led to the initial state - after the program ends - somehow?) Like the way the 'onoff' unexport() function does?

Thanks a lot in advance!

Bitbanged UART?

Very nice project, but it lacks the bitbanged (software) serial read and write function, which the c and python libraries have. This is a very helpful feature which makes it possible to connect more UART devices to the rpi on normal gpio pins. Is there any chance it will be implemented?

Module only accessible when run with sudo

Hey,

I am only able to run the node script with pigpio if I call it with sudo.

If I don't call it with sudo, I get


Sorry, you don't have permission to run this program. Try running as root

Error: pigpio error -1 in gpioInitialise

something throwing max listeners I swear it's not me :-)

using the gpio interrupt

I only set the 'interrupt' listener a single time. Then of course when the pin changes state your code emits an 'interrupt'.

So it's a bit concerning that after a bunch of emits a max listeners is thrown as I have only added a single listener. Are there some behind the scenes events that your code or C code makes listeners for that may either be not removed or not set to .once? cause I can't understand how it's my code since I only set one listener before calling enable. Emitting many times to single listener does not throw this error.

starting interrupt on pin 10
edge= 0
Interrupt occured for 1th time on pin 10
.
.
.
.
Interrupt occured for 110th time on pin 10
Interrupt occured for 111th time on pin 10
Interrupt occured for 112th time on pin 10
Interrupt occured for 113th time on pin 10
Interrupt occured for 114th time on pin 10
(node:2204) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
  let pin = this.interrupts[pin_num].pin
  let edge = this.interrupts[pin_num].edge
  console.log(`starting interrupt on pin ${pin_num}`)
  pin.on('interrupt', this.interruptProcess.bind(this,pin_num))
  // rock n roll!!, start the pigpio interrupt
  console.log('edge=',edge)
  if(!this.mock) pin.enableInterrupt(edge)

Alert and Interrupt events

Whats the difference between the interrupt and alert? As far as I can see the alert is the same as the interrupt but without the options, but the event does get the tick while the interrupt event doesn't receive the tick. What's the reason to not pass this tick along?

Hardware PWM

Hello,

I become more and more confused as PWM seems to me less and less an absolute term.
You declare the word "hardware" a lot in the library, but at the same time, I saw a table that deals with percentages of CPU consumed by varying PWM configurations.

Isn't "Hardware PWM" CPU-independent?
Also, some other library claimed there are only 4 PWM pins on RPI 3 board, while my tests had shown that I could only utilize 2 of them independently, while finally this library seems to be offering all GPIO pins on the board to produce PWM signals.

I'm dazzled with confusion. I'm trying to build a NodeJS quadcopter (so 4 PWM controlled brushless motors) with decent performance and code clarity to be future extension capable.

If you could please help me understand those differing PWM approaches I'll be very thankful...

AsyncResource constructed at the incorrect time

The AsyncResource required for a callback should be constructed when the callback is stored for later invocation. This allows the async context to be restored at the callback invocation time. Currently the AsyncResource is constructed at callback invocation time here and here and doesn't restore the correct async context.

Mocking PiGPIO

Hey guys!
I really enjoy using this lib, however I didn't find a proper way to mock the pigpio on my local machine, so I wrote a simple lib, that copies all methods from this one and prints to console one is invoked.

https://github.com/deepsyx/pigpio-mock

Thought it might be useful :)

npm install error

As I run npm i pigpio I get the following error:

...
319 verbose about to build /home/pi/Desktop/sensorjs/node_modules/pigpio/node_modules/nan
320 info build /home/pi/Desktop/sensorjs/node_modules/pigpio/node_modules/nan
321 info linkStuff [email protected]
322 silly linkStuff [email protected] has /home/pi/Desktop/sensorjs/node_modules/pigpio/node_modules as its parent node_modules
323 verbose linkBins [email protected]
324 verbose linkMans [email protected]
325 verbose rebuildBundles [email protected]
326 info install [email protected]
327 info postinstall [email protected]
328 verbose unlock done using /home/pi/.npm/_locks/nan-541513cab34103a0.lock for /home/pi/Desktop/sensorjs/node_modules/pigpio/node_modules/nan
329 verbose about to build /home/pi/Desktop/sensorjs/node_modules/pigpio
330 info build /home/pi/Desktop/sensorjs/node_modules/pigpio
331 info linkStuff [email protected]
332 silly linkStuff [email protected] has /home/pi/Desktop/sensorjs/node_modules as its parent node_modules
333 verbose linkBins [email protected]
334 verbose linkMans [email protected]
335 verbose rebuildBundles [email protected]
336 verbose rebuildBundles [ 'bindings', 'nan' ]
337 info install [email protected]
338 verbose unsafe-perm in lifecycle true
339 info [email protected] Failed to exec install script
340 verbose unlock done using /home/pi/.npm/_locks/pigpio-341b68c5be5148f0.lock for /home/pi/Desktop/sensorjs/node_modules/pigpio
341 verbose stack Error: [email protected] install: node-gyp rebuild
341 verbose stack Exit status 1
341 verbose stack at EventEmitter. (/home/pi/.nvm/versions/node/v4.0.0/lib/node_modules/npm/lib/utils/lifecycle.js:214:16)
341 verbose stack at emitTwo (events.js:87:13)
341 verbose stack at EventEmitter.emit (events.js:172:7)
341 verbose stack at ChildProcess. (/home/pi/.nvm/versions/node/v4.0.0/lib/node_modules/npm/lib/utils/spawn.js:24:14)
341 verbose stack at emitTwo (events.js:87:13)
341 verbose stack at ChildProcess.emit (events.js:172:7)
341 verbose stack at maybeClose (internal/child_process.js:817:16)
341 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
342 verbose pkgid [email protected]
343 verbose cwd /home/pi/Desktop/sensorjs
344 error Linux 4.1.18-v7+
345 error argv "/home/pi/.nvm/versions/node/v4.0.0/bin/node" "/home/pi/.nvm/versions/node/v4.0.0/bin/npm" "i" "pigpio"
346 error node v4.0.0
347 error npm v2.14.2
348 error code ELIFECYCLE
349 error [email protected] install: node-gyp rebuild
349 error Exit status 1
350 error Failed at the [email protected] install script 'node-gyp rebuild'.
350 error This is most likely a problem with the pigpio package,
350 error not with npm itself.
350 error Tell the author that this fails on your system:
350 error node-gyp rebuild
350 error You can get their info via:
350 error npm owner ls pigpio
350 error There is likely additional logging output above.
351 verbose exit [ 1, true ]
352 verbose unbuild node_modules/pigpio
353 info preuninstall [email protected]
354 info uninstall [email protected]
355 verbose unbuild rmStuff [email protected] from /home/pi/Desktop/sensorjs/node_modules
356 info postuninstall [email protected]
357 silly gentlyRm /home/pi/Desktop/sensorjs/node_modules/pigpio is being purged from base /home/pi/Desktop/sensorjs
358 verbose gentlyRm don't care about contents; nuking /home/pi/Desktop/sensorjs/node_modules/pigpio
359 silly vacuum-fs purging /home/pi/Desktop/sensorjs/node_modules/pigpio
360 silly vacuum-fs removing /home/pi/Desktop/sensorjs/node_modules
361 silly vacuum-fs finished vacuuming up to /home/pi/Desktop/sensorjs

any idea?

Change default port

Is there a way to change the port number that is used by pigpio? The current default is 8888 and this conflicts with an application I'm working on. I know that I could change my port on my application, but I know that pigpiod has the -p parameter which allows for changing of the port that this uses. Unfortunately, it is not possible to run pigpiod and pigpio from within node.js without a conflict.

Thanks...

Craig

PIGPIO on PI3

Hi

I just did an absolutely normal installation of Node-Red and PIGPIO....

When I ran Node-Red (as normal Pi user) - I tried to use PIGPIO and it failed - so I ran Node-Red in the console and tried again after erasing the FLOW file so as to start from scratch.

This is the full Raspbian 17/05/2017 installation.

Here is the part of my script normally used - and used in this case - when installing Node-Red

       if [[ $OPSYS == *"RASPBIAN"* ]]; then
            sudo sed -i -e 's#exit 0#chmod 777 /dev/ttyAMA0\nexit 0#g' /etc/rc.local
            sudo apt-get -y install python{,3}-rpi.gpio 2>&1 | tee -a $LOGFILE
            npm $NQUIET install node-red-contrib-gpio 2>&1 | tee -a $LOGFILE
            npm $NQUIET install raspi-io 2>&1 | tee -a $LOGFILE
        fi

And here is the error from PIGPIO

9 Aug 13:41:29 - [info] Starting flows
1502286089305 Available RaspberryPi-IO
9 Aug 13:41:29 - [info] Started flows
2017-08-09 13:41:29 initCheckPermitted:
+---------------------------------------------------------+
|Sorry, you don't have permission to run this program. |
|Try running as root, e.g. precede the command with sudo. |
+---------------------------------------------------------+

9 Aug 13:41:29 - [red] Uncaught Exception:
9 Aug 13:41:29 - Error: pigpio error -1 in gpioInitialise
at Error (native)
at initializePigpio (/home/pi/.node-red/node_modules/pigpio/pigpio.js:11:12)
at new Gpio (/home/pi/.node-red/node_modules/pigpio/pigpio.js:25:3)
at new DigitalOutput (/home/pi/.node-red/node_modules/raspi-gpio/dist/index.js:79:24)
at RaspiIOCore.value (/home/pi/.node-red/node_modules/raspi-io-core/dist/index.js:553:38)
at RaspiIOCore.pinMode (/home/pi/.node-red/node_modules/raspi-io-core/dist/index.js:505:21)
at /home/pi/.node-red/node_modules/raspi-io-core/dist/index.js:427:17
at Array.forEach (native)
at /home/pi/.node-red/node_modules/raspi-io-core/dist/index.js:356:32
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
pi@pi3:~ $ ^C

pigpio.cc:2:10: fatal error: 'pigpio.h' file not found

  • Node Version:

npm -v
5.4.1

node -v
v8.4.0

  • Platform:

macOS . 10.12.6

  • Compiler:
Apple LLVM version 9.0.0 (clang-900.0.37)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
Verbose output (from npm or node-gyp):
> [email protected] install /Users/roy/development/tjbot-code-challenge/node_modules/fibers
> node build.js || nodejs build.js

  CXX(target) Release/obj.target/fibers/src/fibers.o
../src/fibers.cc:122:18: warning: 'NewFromOneByte' is deprecated [-Wdeprecated-declarations]
                return String::NewFromOneByte(isolate, (const uint8_t*)string);
                               ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:2624:10: note: 'NewFromOneByte' has been explicitly marked deprecated here
  static V8_DEPRECATED(
         ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:126:18: warning: 'NewFromOneByte' is deprecated [-Wdeprecated-declarations]
                return String::NewFromOneByte(isolate, (const uint8_t*)string);
                               ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:2624:10: note: 'NewFromOneByte' has been explicitly marked deprecated here
  static V8_DEPRECATED(
         ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:433:80: warning: 'NewInstance' is deprecated [-Wdeprecated-declarations]
                                return uni::Return(uni::Deref(Isolate::GetCurrent(), tmpl)->GetFunction()->NewInstance(1, argv), args);
                                                                                                           ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:3787:3: note: 'NewInstance' has been explicitly marked deprecated here
  V8_DEPRECATED("Use maybe version",
  ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:621:14: warning: 'TryCatch' is deprecated [-Wdeprecated-declarations]
                                TryCatch try_catch;
                                         ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:8157:3: note: 'TryCatch' has been explicitly marked deprecated here
  V8_DEPRECATED("Use isolate version", TryCatch());
  ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:741:34: warning: 'ToNumber' is deprecated [-Wdeprecated-declarations]
                        Coroutine::pool_size = value->ToNumber()->Value();
                                                      ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:2279:10: note: 'ToNumber' has been explicitly marked deprecated here
  inline V8_DEPRECATED("Use maybe version", Local<Number> ToNumber() const);
         ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:793:8: warning: 'SetAccessor' is deprecated [-Wdeprecated-declarations]
                        fn->SetAccessor(uni::NewLatin1Symbol(isolate, "current"), GetCurrent);
                            ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:3120:3: note: 'SetAccessor' has been explicitly marked deprecated here
  V8_DEPRECATED("Use maybe version",
  ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:794:8: warning: 'SetAccessor' is deprecated [-Wdeprecated-declarations]
                        fn->SetAccessor(uni::NewLatin1Symbol(isolate, "poolSize"), GetPoolSize, SetPoolSize);
                            ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:3120:3: note: 'SetAccessor' has been explicitly marked deprecated here
  V8_DEPRECATED("Use maybe version",
  ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
../src/fibers.cc:795:8: warning: 'SetAccessor' is deprecated [-Wdeprecated-declarations]
                        fn->SetAccessor(uni::NewLatin1Symbol(isolate, "fibersCreated"), GetFibersCreated);
                            ^
/Users/roy/.node-gyp/8.4.0/include/node/v8.h:3120:3: note: 'SetAccessor' has been explicitly marked deprecated here
  V8_DEPRECATED("Use maybe version",
  ^
/Users/roy/.node-gyp/8.4.0/include/node/v8config.h:332:29: note: expanded from macro 'V8_DEPRECATED'
  declarator __attribute__((deprecated))
                            ^
8 warnings generated.
  CXX(target) Release/obj.target/fibers/src/coroutine.o
  CC(target) Release/obj.target/fibers/src/libcoro/coro.o
  SOLINK_MODULE(target) Release/fibers.node
Installed in `/Users/roy/development/tjbot-code-challenge/node_modules/fibers/bin/darwin-x64-57/fibers.node`

> [email protected] install /Users/roy/development/tjbot-code-challenge/node_modules/pigpio
> node-gyp rebuild

  CXX(target) Release/obj.target/pigpio/src/pigpio.o
../src/pigpio.cc:2:10: fatal error: 'pigpio.h' file not found
#include <pigpio.h>
         ^~~~~~~~~~
1 error generated.
make: *** [Release/obj.target/pigpio/src/pigpio.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:258:23)
gyp ERR! stack     at emitTwo (events.js:125:13)
gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 16.7.0
gyp ERR! command "/usr/local/Cellar/node/8.4.0/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/roy/development/tjbot-code-challenge/node_modules/pigpio
gyp ERR! node -v v8.4.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok 

There is no debounce to use push buttons

Please add a debounce function or code to make push buttons work with node.js.
I'm getting interference from lights and refrigerator that my raspberry assume is a button pushed.

node-gyp rebuild fails

Error: http://pastebin.com/ztq29Ekb

Node version: v7.7.0 (Installed manually)

Pi: Using the new Pi Zero W :)

Getting this error when trying to install this package. It might be because of my non-ordinary node install method. I did notice that I didn't see the "you don't have to install pigpio as it's included in raspbian" sentence, so I did install pigpio. I don't think that causes this problem.

Edit: I cleaned my Node install, and used NVM to do a new install, but the same problem occurs.

pigpio.initialize() doenst do its job after pigpio.terminate()

I have a situation in which I use pigpio in Node and in native C
Thus I need to call pigpio.terminate() in Node before I can call pigpio in C otherwise C complains about not getting the lock on the pid.
When I then try to call pigpio.initialize in Node again it doesnt seem to work since I get the message:

calling initialize
Hardware Revision: 9000c1
initialized= 1
2017-09-17 18:45:59 gpioSetMode: pigpio uninitialised, call gpioInitialise()


var initialized;
var pigpio = require('pigpio')
var Gpio=pigpio.Gpio

 exports.test = function(led_nr, dutyCycle) {	
	if (!initialized)	{
		console.log("calling initialize");
		pigpio.initialize(); // pigpio C library initialized here
		initialized=1;
		console.log('Hardware Revision: ' + pigpio.hardwareRevision().toString(16));
		test_led(led_nr, dutyCycle);   
	}
	else 
		test_led(led_nr, dutyCycle);    //called function to make sure I dont get race conditions
	
	
};	

exports.terminate = function() {
	console.log("initialized= " + initialized);
	if (initialized)	{
		pigpio.terminate(); // pigpio C library terminated here
		initialized=0;
		console.log("initialized= " + initialized);
		console.log('Terminated');
	}	//end if
};//end terminate

    function test_led(led_nr, dutyCycle)	{
	console.log("initialized= " + initialized);
	led = Gpio(led_nr, {mode: Gpio.OUTPUT}); 
	
	led.pwmRange(100)
	led.pwmWrite(dutyCycle);
}

Versions:

pigpio: "_id": "[email protected]",
node v6.11.3

I expirience no problems with the C version of the pigpio library - hence I would assume its an issue with the wrapper.

free port when application finishes

Problem: pigpio binds on port 8888. when app shuts down the port remains bound. Subsequently, when the app is run again it fails with following error message.

 initInitialise: bind to port 8888 failed (Address already in use)
/home/pi/verifiedcut/webapp-server/node_modules/pigpio/pigpio.js:11
    pigpio.gpioInitialise();
           ^

Error: pigpio error -1 in gpioInitialise
    at Error (native)
    at initializePigpio (/home/pi/verifiedcut/webapp-server/node_modules/pigpio/pigpio.js:11:12)
    at new Gpio (/home/pi/verifiedcut/webapp-server/node_modules/pigpio/pigpio.js:25:3)
    at Object.<anonymous> (/home/pi/verifiedcut/webapp-server/server.js:254:29)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)

I expected to see/use the C pigpio gpioTerminate method. Is this method exposed in the binding? How do I properly terminate app?

Successive crashes/restarts makes alerts unresposive.

I've read all I can find here, and everything works as expected, the Alert event with the microsecond tick is great, but I have on nagging issue:

During tests, with ctrl-c or crashes, (not a repeatable number or precise situation) the Alerts stop being generated and the only fix that I have found is to reboot my Pi. I am not using any special signal handling routines. I'm only watching one pin while writing to several others. I seem to be able to continue reading and writing states, but no interrupts/alerts. Is this just me?

I'm on node 8.9.3 LTS and A 4.9.70-v7+ Kernel on a Pi-3 B+ with a 1.60 version of the pigpio C library.

Java Native Interface sigHandler: Unhandled signal 11, terminating

When using pigpio in Java through JNI the program terminates with

sigHandler: Unhandled signal 11, terminating

this happens when using interrupt functions such as gpioSetAlertFunc or gpioSetISTFunc even if these functions do absolutely nothing.

This might be a JNI issue. If anyone has any ideas on how to use pigpio interrupts in Java I would greatly appreciate any suggestions.

I updated to latest java
java version "1.8.0_131"

void interrupt_s(int gpio, int level, uint32_t tick)
{
   /*
      Callback does nothing
   */
}


JNIEXPORT jlong JNICALL Java_pigpioTest
  (JNIEnv *env, jobject obj, jint pin)
{
	//Initialize PIGPIO library
	if (gpioInitialise() < 0) {
		return 0;
	}
        // Set a single pin as input
	gpioSetMode(pin, PI_INPUT);
	gpioSetPullUpDown(pin, PI_PUD_DOWN);
	   /* monitor pin level changes */
	gpioSetAlertFunc(pin, interrupt_s);
	return 1;
}

The above runs for a while and then the sigHandler: Unhandled signal 11, terminating error happens.

.h

pigpio.h missing

configureClock() doesn't seem to work

I can't get configureClock(microseconds, peripheral) to do anything - probably it's just me doing it wrong so I'm sorry this might not be an issue but more of a question - how to use configureClock() so to set resolution to 2 instead of default 5?

Error -123 in gpioSetISRFunc

I've created a js file that captures motion from a PIR sensor on a Raspberry Pi and and trying to test it but I get this error when I run it:

pi@raspberrypi:~/squirrel $ sudo "$(which node)" soundtest.js
1514575499162 Available RaspberryPi-IO
1514575499514 Connected RaspberryPi-IO
1514575499524 Repl Initialized
>> starting
/home/pi/squirrel/node_modules/pigpio/pigpio.js:137
  pigpio.gpioSetISRFunc(this.gpio, +edge, +timeout, handler);
         ^
Error: pigpio error -123 in gpioSetISRFunc
    at Gpio.enableInterrupt (/home/pi/squirrel/node_modules/pigpio/pigpio.js:137:10)
    at new DigitalInput (/home/pi/squirrel/node_modules/raspi-gpio/dist/index.js:116:22)
    at RaspiIOCore.value (/home/pi/squirrel/node_modules/raspi-io-core/dist/index.js:550:38)
    at RaspiIOCore.pinMode (/home/pi/squirrel/node_modules/raspi-io-core/dist/index.js:505:21)
    at Motion.value (/home/pi/squirrel/node_modules/johnny-five/lib/motion.js:29:17)
    at new Motion (/home/pi/squirrel/node_modules/johnny-five/lib/motion.js:185:10)
    at Board.<anonymous> (/home/pi/squirrel/soundtest.js:11:16)
    at emitNone (events.js:111:20)
    at Board.emit (events.js:208:7)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)

I'm not really sure what this means. The code that I am running is:

const player = require('play-sound')();

const raspi = require('raspi-io');
const five = require('johnny-five');
const board = new five.Board({io: new raspi()});

board.on("ready", function() {

  // Create a new `motion` hardware instance.
  console.log('starting')
  let motion = new five.Motion('P1-7');
  // "calibrated" occurs once, at the beginning of a session,
  motion.on("calibrated", function() {
    console.log("calibrated");
  });
...do things with the motion
});

I'm using Node 8.9.3 and pigpio 0.6.4. If you have any advice, I would greatly appreciate it. Thanks!

Edit: Adding that this is on Raspbian Stretch lite, 4.9.59-v7+, Pi-3B, pigpio 1.64-1 library

Using internal pull up/down resistor causes constant interrupts

I dunno if this is a fault in my wiring or a software issue. I have the following code:

button= new Gpio(pin, {
        mode: Gpio.INPUT,
        pullUpDown : Gpio.PUD_DOWN,
        edge : Gpio.EITHER_EDGE
})
button.on("interrupt", function(level){
        console.log("Pin", pin, "Level", level)
})

With my wiring being GPIO -> Button -> 3v3

The levels are proper, so it's not floating, but the interrupt function runs constantly.

However, when I make a proper pull down setup using external resistors, it works fine and only interrupts when I actually hit or release the button. Am I missing something?

This is tested on a v2 B+, and v3 with the same results.

MPC23017 example?

Are there any examples for using with a port expander like MPC23017?

fork in node causes error on the second child

running a script where
const child_process = require('child_process');
var kicker_process = child_process.fork(${__dirname}/botjs/ki.js); //
in ki.js we have
var pigpio = require('pigpio'), pig= pigpio.Gpio
ki_process = new Ki(pig,18);
ki_process.init();

all works good. But if you have a second child_process.fork with a
var pigpio = require('pigpio'), pig= pigpio.Gpio
in it. it fails in initallising it. pigpio line 11.
It should work.
I have many sensors that have their own js file. all plan to run in a child_process fork. All planning to use pigpio. I can only run one child process that uses pigpio in it at the moment.

HELP with Measure distance with a HC-SR04 ultrasonic sensor

Hi, i'm sorry it is not a issue but more an help request. I am new to the NODE JS and javascript world.
I try the code for the "Measure distance with a HC-SR04 ultrasonic sensor" and it's working. Thanks for that.

Nevertheless, i don't understand the syntax of this part of code:
We declare an async anonymous function with a callback function inside the echo.on ?

(function () {
  var startTick;

  echo.on('alert', function (level, tick) {
    var endTick,
      diff;

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

How can i retrieve the distance from outside this callback function and anonymous function ?
A struggle few hours on this.
Thanks a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.