Code Monkey home page Code Monkey logo

rpi-gpio.js's Introduction

rpi-gpio.js

Control Raspberry Pi GPIO pins with node.js

Build Status NPM version

Supported hardware

  • Raspberry Pi 1 Model A
  • Raspberry Pi 1 Model A+
  • Raspberry Pi 1 Model B
  • Raspberry Pi 1 Model B+
  • Raspberry Pi 2 Model B
  • Raspberry Pi 3 Model B
  • Raspberry Pi 4 Model B
  • Raspberry Pi Zero
  • Raspberry Pi Zero W

Supported node versions

rpi-gpio 1.x is no longer supported. Please use 2.x unless you need to run with an old version of node.

node version rpi-gpio 1.x rpi-gpio 2.x +
0.10 Yes No
0.12 Yes No
4 Yes Yes
6 Yes Yes
8 Yes Yes
10 No Yes
12 No Yes

Setup and install

See this guide on how to get node.js running on Raspberry Pi.

This module can then be installed with npm:

npm install rpi-gpio

Dependency

Please note that this module has a dependency on epoll and that currently it is only possible to build and develop the module on Linux systems.

If you are having trouble installing this module make sure you are running gcc/g++ -v 4.8 or higher. Here is an installation guide.

Typescript

If you wish to use this module with Typescript, install the definitions from Definitely Typed:

npm install --save @types/rpi-gpio

Please note that this is not a Typescript project and the definitions are independently maintained by the community. Thanks to Roaders for providing these.

Usage

Before you can read or write, you must use setup() to open a channel, and must specify whether it will be used for input or output. Having done this, you can then read in the state of the channel or write a value to it using read() or write().

All of the functions relating to the pin state within this module are asynchronous, so where necessary - for example in reading the value of a channel - a callback must be provided. This module inherits the standard EventEmitter, so you may use its functions to listen to events.

Pin naming

Please be aware that there are multiple ways of referring to the pins on the Raspberry Pi. The simplest and default way to use the module is refer to them by physical position, using the diagrams on this page. So holding the Raspberry Pi such that the GPIO header runs down the upper-right side of the board, if you wished to address GPIO4 (which is in column 1 and row 4), you would setup pin 7. If you wish instead to refer to the pins by their GPIO names (known as BCM naming), you can use the setMode command described in the API documentation below.

Running without sudo

This module will work without use of the sudo command, as long as the user running the node process belongs to the gpio group. You can check the current user's groups by running the command groups, or groups <user> for another user. If you are not already a member of the gpio group, you can add yourself or another user by running sudo adduser <user> gpio.

API (Error-first)

The default API uses the node-style error-first callbacks to perform asynchronous functions. Most of these methods take a callback, and that callback should check for an error in its first argument. It is important to check for an error after each command, else your code will continue to run and will likely fail in hard to understand ways.

Methods

setup(channel [, direction, edge], callback)

Sets up a channel for read or write. Must be done before the channel can be used.

  • channel: Reference to the pin in the current mode's schema.
  • direction: The pin direction, pass either DIR_IN for read mode or DIR_OUT for write mode. You can also pass DIR_LOW or DIR_HIGH to use the write mode and specify an initial state of 'off' or 'on' respectively. Defaults to DIR_OUT.
  • edge: Interrupt generating GPIO chip setting, pass in EDGE_NONE for no interrupts, EDGE_RISING for interrupts on rising values, EDGE_FALLING for interrupts on falling values or EDGE_BOTH for all interrupts. Defaults to EDGE_NONE.
  • callback: Provides Error as the first argument if an error occurred.

read(channel, callback)

Reads the value of a channel.

  • channel: Reference to the pin in the current mode's schema.
  • callback: Provides Error as the first argument if an error occured, otherwise the pin value boolean as the second argument.

write(channel, value [, callback])

Writes the value of a channel.

  • channel: Reference to the pin in the current mode's schema.
  • value: Boolean value to specify whether the channel will turn on or off.
  • callback: Provides Error as the first argument if an error occured.

setMode(mode)

Sets the channel addressing schema.

  • mode: Specify either Raspberry Pi or SoC/BCM pin schemas, by passing MODE_RPI or MODE_BCM. Defaults to MODE_RPI.

input()

Alias of read().

output()

Alias of write().

destroy()

Tears down any previously set up channels. Should be run when your program stops, or needs to reset the state of the pins.

reset()

Tears down the module state - used for testing.

Events

See Node EventEmitter for documentation on listening to events.

change

Emitted when the value of a channel changed

  • channel
  • value

API (Promises)

This API exposes a Promises interface to the module. All of the same functions are available, but do not take callbacks and instead return a Promise.

The Promises interface is available in the promise namespace, e.g.:

var gpiop = require('rpi-gpio').promise;

gpiop.setup(7, gpiop.DIR_OUT)
    .then(() => {
        return gpiop.write(7, true)
    })
    .catch((err) => {
        console.log('Error: ', err.toString())
    })

Examples

See the examples directory included in this project.

Please note that all examples are intended to be directly runnable from the code repository, so they always require the module in at the top using var gpio = require(../rpi-gpio). In reality, you will want to include the module using var gpio = require('rpi-gpio')

Contributing

Contributions are always appreciated, whether that's in the form of bug reports, pull requests or helping to diagnose bugs and help other users on the issues page.

Due to the nature of this project it can be quite time-consuming to test against real hardware, so the automated test suite is all the more important. I will not accept any pull requests that cause the build to fail, and probably will not accept any that do not have corresponding test coverage.

You can run the tests with npm:

npm test

and create a coverage report with:

npm run coverage

There is also an integration test that you can run on Raspberry Pi hardware, having connected two GPIO pins across a resistor. The command to run the test will provide further instructions on how to set up the hardware:

npm run int

The tests use mochajs as the test framework, and Sinon.JS to stub and mock out file system calls.

rpi-gpio.js's People

Contributors

aleksipirttimaa avatar andrewdotn avatar aslafy-z avatar aztecrex avatar dawn-minion avatar dependabot[bot] avatar jamesbarwell avatar jamesbulpin avatar julienvincent avatar pimterry avatar robertkowalski avatar thecodershome 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

rpi-gpio.js's Issues

Unhandled permission error leads to [Error: Pin has not been exported]

I'm trying to setup/read using this library but i'm getting "Pin has not been exported" error, here is my code:

gpio.setup 23, gpio.DIR_IN, gpio.EDGE_BOTH, ( error, data ) ->

  gpio.read 23, ( error, data ) ->

    if error then return console.log 'error reading', error

    console.log data

here is the error:

error reading [Error: Pin has not been exported]

if i manually export and try to read via gpio it works //=

echo 23 > /sys/class/gpio/export
gpio read 23
0
gpio read 23
1

rPi 2, model B

"export" races udev's resetting of sysfs permissions, causing library to unnecessarily require root.

On Rasbian Jessie, the system comes with a gpio group and udev is configured to change the sysfs permissions such that everything in /sys/class/gpio is writeable by group gpio.

https://github.com/RPi-Distro/raspberrypi-sys-mods/blob/master/etc/udev/rules.d/99-com.rules#L6

In theory, this should allow gpio access for all users in the gpio group without needing root or sudo. However, rpio-gpio seems to consistently get EACCES when attempting to set the edge configuration. It seems what is happening (verified by adding a fs.statSync call as well as watching via strace) is the library is accidentally racing udev's permission reset here:

https://github.com/JamesBarwell/rpi-gpio.js/blob/master/rpi-gpio.js#L183

Furthermore, since the library conservatively unexports the pin if it is exported (https://github.com/JamesBarwell/rpi-gpio.js/blob/master/rpi-gpio.js#L176), it actually causes the race condition to almost always trigger even when the code is executed multiple times.

If at line 183, you add another waterfall stage:

            function(next) {
              setTimeout(next, 5000);  // Just wait 5 seconds.
            }

between the exportPin and setEdge calls, the code will succeed for users in the gpio group w/o requiring root.

Not quite sure what the "right" fix is here, but 2 thoughts:
(1) Don't unexport the pin if it's already exported.
(2) Use inotify or something and watch for permissions changes to the /sys/class/gpi/gpiXX directory with a timeout before continuing on the waterfall?

pin turn off during the 'read' operation.

This is my code:

exports.get = function(pin){ // perchè il file functions.js è incluso esternamente

gpio.setup(pin, gpio.DIR_IN, read_state);

function read_state() {
        gpio.read(pin, function(err, value) {
            var state = (value) ? "on": "off"; // The current state of the pin (true: on or false: off)
            console.log("The value is: "+state);
            return {response_code: 200, new_state: stato, path: "/toggle"};
        });
}
gpio.destroy();

};

When i call exports.get(11) it actually turns off the gpio 11 and print 'the value is: off'.

Why is turning off the Pin? o.O

'gpio.on' binding not working on PI2

I am trying out this library and I am not unable to follow the examples since the callback functions to gpio.on 'change' and 'export' are not being triggered. I notice that RPI2 is not mentioned anywhere on this repo. Do you support RPI2 ?

Cannot open pin for read

Im running raspi Model B Rev 2 512MB, I installed the module and succesfully opened a pin for writing on it. Succesfully made a LED blink.
Then I try to open a port for reading and I get and error

{ Error: EINVAL: invalid argument, write errno: -22, code: 'EINVAL', syscall: 'write' }

This the relevant part of the code.

var gpio = require('rpi-gpio');
server.listen(8080, function() {
	console.log('Servidor corriendo en http://localhost:8080');
	
	gpio.setup(7, gpio.DIR_OUT, control);
	gpio.setup(6, gpio.DIR_IN, control);
});

function control(err)
{
	if(err)
		console.log("Control function: " + err);
	else
		console.log('ok');
}

Any clue ??

Raspberry Pi 3 B

I have used this module for the Raspberry Pi 3 model B successfully. It should be added to the list of supported devices.

Error: EPERM, write on boot

I have an init.d script to restart the app if loss of power etc. This script calls:

sudo -u pi NODE_ENV=production forever --sourceDir $APPDIR start app.js

which works fine if I call it directly

sudo /etc/init.d/nodeboot.sh start

but upon reboot i get Error: EPERM, write when attempting to access any pins

gpio.write(7, true, function(err) {
            if (err) throw err;
        });

any ideas on why it might throw that error?

Regex not correctly detecting my rpi v2

The line at:

https://github.com/JamesBarwell/rpi-gpio.js/blob/master/rpi-gpio.js#L227

That currently reads:

var match = data.match(/Revision\s*:\s*\d*(\d{4})/);

Needs to be changed to:

var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);

Because my rpi /proc/cpuinfo is:

processor       : 0
model name      : ARMv6-compatible processor rev 7 (v6l)
Features        : swp half thumb fastmult vfp edsp java tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x0
CPU part        : 0xb76
CPU revision    : 7

Hardware        : BCM2708
Revision        : 000e
Serial          : 00000000f5fec704

As you can see, the Revision value is really an hexadecimal number.

Maybe you should just try to parse the value as an hexadecimal number and assume its v1 when its values is < 3 and v2 otherwise.

See http://elinux.org/RPi_HardwareHistory#Board_Revision_History

pin as function parameter?

So I get how this works..

var pin = 3;
gpio.setup(pin, gpio.DIR_OUT, on);

function on() {
    gpio.write(pin, 1);
}

how would I go about doing something like..

gpio.setup(1, gpio.DIR_OUT);
gpio.setup(2, gpio.DIR_OUT);
gpio.setup(3, gpio.DIR_OUT);

on(3);

function on(pin) {
    gpio.write(pin, 1);
}

I keep on getting return currentPins[channel] + ''; .. TypeError: Cannot read property '3' of undefined errors

RPI2: OK

It is ok with the RPI2, as it is using the fs controls. At least it works for me.

Use promise instead of callback

Use promise https://github.com/kriskowal/q to be able to stack them. Very usefull in order to wait for all setup to be finished.

Instead of (ES6) :

gpio.setup(40, gpio.DIR_OUT, err => {
   if (err) { throw err; }
   gpio.setup(38, gpio.DIR_OUT, err => {
     if (err) { throw err; }
     gpio.setup(37, gpio.DIR_OUT, err => {
        if (err) { throw err; }
        // do something
     }
   }
});

use :

gpio.setup(40, gpio.DIR_OUT).then(() => {
   // do something
   return gpio.setup(38, gpio.DIR_OUT);
}).then(() => {
   return gpio.setup(37, gpio.DIR_OUT);
}).then(() => {
   // do something
}).catch(err => {
   throw err;
}

Exemple of implementation in rpi-gpio.js :

fs.writeFile(PATH + '/gpio' + pin + '/value', value, cb);

become

var deferred = q.defer();
fs.writeFile(PATH + '/gpio' + pin + '/value', value, (err) => {
   if (err) { 
      deferred.reject(err); 
   } else { 
      deferred.resolve();
   }
});
return deferred.promise;

PWM??

Can I use pwm with this module. I want to supply half voltage to the pins.

I tried:
gpio.write(pin.number, 0.5, function() {});

but it does not seem to work.

read pins value not right

var lPins = [31,33,35,37]

lPins.forEach(function(channel){
        gpio.setup(channel, gpio.DIR_IN, gpio.EDGE_NONE );
})

lPins.forEach(function(channel){
            gpio.read(channel, function(err, value) {
                    console.log(channel + 'The value is ' + value);
            });
})

I didn't do anything but the value changed

31The value is true
33The value is true
35The value is true
37The value is true

31The value is false
33The value is false
35The value is false
37The value is false

31The value is true
33The value is true
35The value is true
37The value is true

31The value is false
33The value is false
35The value is false
37The value is false

31The value is true
33The value is true
35The value is true
37The value is true

gpio.EDGE_BOTH EIO: i/o error, write

rpi-gpio throws on setting up pin 7 for listening:

'use strict';

const bunyan = require('bunyan');
const log = bunyan.createLogger({ name: 'RPI button app' });
const gpio = require('rpi-gpio');
const express = require('express');
const app = express();

gpio.on('change', (channel, value) => {
    log.info('Channel ' + channel + ' value is now ' + value);
});

gpio.setup(7, gpio.DIR_OUT, gpio.EDGE_BOTH, err => {
    if (err) throw err;
});

Gives me:

pi@raspberrypi ~/Git/rpi-button-app $ sudo nodemon ./index.js 
/home/pi/Git/rpi-button-app/index.js:14
    if (err) throw err;
             ^

Error: EIO: i/o error, write
    at Error (native)

Running Raspbian wheezy, node v4.4.7 on a v1 B Pi.
I could just set up a time interval, as the normal read and write are working fine. But I rather like the evented feature of rpi-gpio :)

Thanks for any pointers

Error using Raspberry PI 2

I'm trying to use this module on my new Raspberry Pi 2 and i have this error:

Error: Pin has not been exported 
at /home/pi/Projects/nodejs/node_modules/rpi-gpio/rpi-gpio.js:205:20
at process._tickCallback (node.js:355:11) 
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3

I'm trying top open a pin and then write to it using a a custom callback in this way.

var gpio = require('rpi-gpio');
gpio.setup(pin,gpio.DIR_OUT,write(pin,false))

I'm using:
sudo command;
node version: 0.12.1;

BCM mode not working ?

if i try gpio.setup with GPIO BCM 17 a receive this error "Channel 17 does not map to a GPIO pin

running without sudo

Because it's bad for obvious reasons, I would like to run my script without sudo.
Do you have any approaches to realize this?

fs has no method 'exists' ?

This is the stack trace of error.
/home/pi/node_modules/rpi-gpio/rpi-gpio.js:376
fs.exists(PATH + '/gpio' + pin, function(exists) {
^
TypeError: Object # has no method 'exists'
at isExported (/home/pi/node_modules/rpi-gpio/rpi-gpio.js:376:8)
at /home/pi/node_modules/rpi-gpio/rpi-gpio.js:160:17
at /home/pi/node_modules/rpi-gpio/node_modules/async/lib/async.js:641:34
at Array.0 (/home/pi/node_modules/rpi-gpio/node_modules/async/lib/async.js:557:34)
at EventEmitter._tickCallback (node.js:190:39)

Module version mismatch. Expected 50, got 48.

I'm trying to use rpi-gpio within electron and get the following error, not sure what it says. Would be very thankful for any help!

bindings.js:83 Uncaught Error: Module version mismatch. Expected 50, got 48.module.(anonymous function) @ ELECTRON_ASAR.js:168Module._extensions..node @ module.js:583module.(anonymous function) @ ELECTRON_ASAR.js:168Module.load @ module.js:473tryModuleLoad @ module.js:432Module._load @ module.js:424Module.require @ module.js:483require @ internal/module.js:20bindings @ bindings.js:76(anonymous function) @ epoll.js:1Module._compile @ module.js:556require.extensions.(anonymous function) @ require-hook.js:17Module.load @ module.js:473tryModuleLoad @ module.js:432Module._load @ module.js:424Module.require @ module.js:483require @ internal/module.js:20(anonymous function) @ rpi-gpio.js:6Module._compile @ module.js:556require.extensions.(anonymous function) @ require-hook.js:17Module.load @ module.js:473tryModuleLoad @ module.js:432Module._load @ module.js:424Module.require @ module.js:483require @ internal/module.js:20(anonymous function) @ index.html:inline_0.js:26

GPIO bouncing

I am using one GPIO pin as output to drive a relay. Every time I send a command to switch on the relay I listen that the relay is switched on, off an finally on. I didn’t have any clue what's causing this behaviour. I am using the example code available on the rpi-gpio.js.

Error while installing

pi@raspberrypi:~/aquarium_monitor $ npm install rpi-gpio
\

[email protected] install /home/pi/aquarium_monitor/node_modules/rpi-gpio/node_modules/epoll
node-gyp rebuild

make: Entering directory '/home/pi/aquarium_monitor/node_modules/rpi-gpio/node_modules/epoll/build'
CXX(target) Release/obj.target/epoll/src/epoll.o
In file included from ../src/epoll.cc:15:0:
../node_modules/nan/nan.h:328:47: error: ‘REPLACE_INVALID_UTF8’ is not a member of ‘v8::String’
static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
^
epoll.target.mk:84: recipe for target 'Release/obj.target/epoll/src/epoll.o' failed
make: *** [Release/obj.target/epoll/src/epoll.o] Error 1
make: Leaving directory '/home/pi/aquarium_monitor/node_modules/rpi-gpio/node_modules/epoll/build'
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/share/node-gyp/lib/build.js:267:23)
gyp ERR! stack at ChildProcess.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:809:12)
gyp ERR! System Linux 4.1.13+
gyp ERR! command "nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /home/pi/aquarium_monitor/node_modules/rpi-gpio/node_modules/epoll
gyp ERR! node -v v0.10.29
gyp ERR! node-gyp -v v0.12.2
gyp ERR! not ok
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the epoll package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls epoll
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 4.1.13+
npm ERR! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "rpi-gpio"
npm ERR! cwd /home/pi/aquarium_monitor
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.21
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/pi/aquarium_monitor/npm-debug.log
npm ERR! not ok code 0
pi@raspberrypi:~/aquarium_monitor $

Calling a read function from another module

Hello, I'm having some throuble with calling a read funcion from another module.
This is the module I am using for reading a gpio:

var gpio = require('rpi-gpio');

gpio.setup(inGpio, gpio.DIR_IN, read.readInput);

var readInput = function(inGpio) { 
    console.log('Read Input on: ' + inGpio + 'GPIO initializing...');  
    return gpio.read(inGpio, function(err, value) {
        console.log('The value is ' + value);
    });
}
exports.readInput = readInput;

In this case, the inGpio in the setup is not defined then causes me a error.

And this is how I am calling it:

var readSwitch = function(gpio){
    console.log('swtichFactory.readSwitch initializing...');
    return read.readInput(gpio);   

}

If I put the gpio.setup inside the function I got 'The value is undefined'.
Someone know how I can solve this ?

Unable to install on Node 4.0.0

I'm getting a node-gyp-rebuild error while installing rpi-gpio on node 4.0.0.

Command: pi@raspberrypi ~/node_projects/gpio $ sudo npm install -g --unsafe-perm rpi-gpio

Any idea what's going on? I was told to try the unsafe-perm and it should help. Here's the output from that:

http://pastebin.com/MkfWUnbY

Pin has not been exported for write

Hi, I've just started using rpi-gpio and wanted to try out the functions. I'm trying to write to a pin (7) but I'm getting the following error:

Pin has not been exported for write

Node: v6.3.0
Raspbian: 8.0 Jessie

If the project is still active, any advice would be great.
Thanks.

Simply requiring the module generates a `cannot self-register` error

I'm running on node 5.x, and just requiring the module generates this error:

> require('rpi-gpio')
Error: Module did not self-register.
    at Error (native)
    at Object.Module._extensions..node (module.js:423:18)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at bindings (/Users/julienvincent/code/test/node_modules/bindings/bindings.js:76:44)
    at Object.<anonymous> (/Users/julienvincent/code/test/node_modules/epoll/epoll.js:1:99)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
>

I will attempt to fix this, but so long I'm just letting everyone know. I guess this is caused by epoll? I'm not sure.

README suggestion

GPIO5 is on pin 29.

"Please note that there are two different and confusing ways to reference a channel; either using the Raspberry Pi or the BCM/SoC naming schema (sadly, neither of which match the physical pins!). This module supports both schemas, with Raspberry Pi being the default. Please see this page for more details."

The above does not help me figure out if I should use 5 or 29 since the raspberry documentation refers to pin29 as GPIO5.

Example for "change" listener throws error

This code:

var gpio = require('rpi-gpio');
gpio.on('change', function(channel, value) {
    console.log('Channel ' + channel + ' value is now ' + value);
});
gpio.setup(7, gpio.DIR_IN);

Results in:

/path/node_modules/rpi-gpio/rpi-gpio.js:355
        if (cb) return cb(err);
                       ^
TypeError: string is not a function
    at /path/node_modules/rpi-gpio/rpi-gpio.js:355:24
    at fs.js:944:21
    at Object.oncomplete (fs.js:107:15)

Simple reads of the pin (via your other example) do work, so I don't believe that it's my setup.

Maintainer stagnation

It's beginning to look like this repository is no longer actively maintained, with issues and a couple good PR's popping up.

@JamesBarwell I understand you may be busy/unable to actively maintain this library, but this is quite a popular library and is continuously gaining followers. This inactivity is hurting the repo.

I'd like to see this repository grow and be improved, but in order for that to happen - something needs to change.

WatchFile not working

the on change event doesn't work, however I have traced the issue back to the fact that watchFile does not detect changes in the gpio files. I managed to rig up a ghetto watcher by setInterval and comparing the values then calling a function, but that is bad.

Is there a fix/replacement for this?

Event Listener gets undefined value

Running your example code (copy and paste):

var gpio = require('rpi-gpio'):
var pin   = 7;
var delay = 2000;
var count = 0;
var max   = 3;

gpio.on('change', function(channel, value) {
    console.log('Channel ' + channel + ' value is now ' + value);
});
gpio.setup(pin, gpio.DIR_OUT, on);

function on() {
    if (count >= max) {
        gpio.destroy(function() {
            console.log('Closed pins, now exit');
            return process.exit(0);
        });
        return;
    }

    setTimeout(function() {
        gpio.write(pin, 1, off);
        count += 1;
    }, delay);
}

function off() {
    setTimeout(function() {
        gpio.write(pin, 0, on);
    }, delay);
}

The led attached to pin 7 (gpio4) is blinking but the event listener on('change'...) fires with value undefined. Here's my console logs:

Channel 7 value is now undefined
Channel 7 value is now undefined
Closed pins, now exit

Note also that the event listener is fired just twice, but that should be normal since the language is asynchronous.

Running without root permission

I am using v0.8.1 and i get following error when I try to run this application without root permission. It works perfectly with root.

Error: Pin has not been exported for write
at /var/www/smartlyteplus/node_modules/rpi-gpio/rpi-gpio.js:243:20
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

Here is my code

var gpioDriver = require('rpi-gpio');

function setPin(pin, state, cb){
    gpioDriver.setup(pin, gpioDriver.DIR_OUT, function(){
        gpioDriver.write(pin, state, function(err){
            if(err){
                return cb(err);
            }
            return cb();
        });
    });
}

Error: Could not locate the bindings file.

node a.js
/home/pi/server/node_modules/bindings/bindings.js:91
  throw err
  ^

Error: Could not locate the bindings file. Tried:
 → /home/pi/server/node_modules/epoll/build/epoll.node
 → /home/pi/server/node_modules/epoll/build/Debug/epoll.node
 → /home/pi/server/node_modules/epoll/build/Release/epoll.node
 → /home/pi/server/node_modules/epoll/out/Debug/epoll.node
 → /home/pi/server/node_modules/epoll/Debug/epoll.node
 → /home/pi/server/node_modules/epoll/out/Release/epoll.node
 → /home/pi/server/node_modules/epoll/Release/epoll.node
 → /home/pi/server/node_modules/epoll/build/default/epoll.node
 → /home/pi/server/node_modules/epoll/compiled/4.2.1/linux/arm/epoll.node
    at bindings (/home/pi/server/node_modules/bindings/bindings.js:88:9)
    at Object.<anonymous> (/home/pi/server/node_modules/epoll/epoll.js:1:99)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at Object.<anonymous> (/home/pi/server/node_modules/rpi-gpio/rpi-gpio.js:6:20)
    at Module._compile (module.js:435:26)

npm is 2.14.7, nodejs is 4.2.1, rpi-gpio is 0.7.0

cat /proc/version 
Linux version 4.1.19-v7+ (dc4@dc4-XPS13-9333) (gcc version 4.9.3 (crosstool-NG crosstool-ng-1.22.0-88-g8460611) ) #858 SMP Tue Mar 15 15:56:00 GMT 2016
gcc --version
gcc (Raspbian 4.9.2-10) 4.9.2
g++ --version
g++ (Raspbian 4.9.2-10) 4.9.2

a.js is

var gpio = require('rpi-gpio');

THE SOLUTION
npm rebuild

High poll frequency on pin change events

The current file listener uses the default poll frequency of fs.watchFile (5007ms). This means the change event is not reliably triggered when, for example, an LED is flashed on/off every 500ms.

I think there are a couple of options,

  1. Use fs.watch instead, however this seems to be less widely supported.
  2. Add a setPollFrequency() function to allow the user to override the default value.

Do you have a preference?

Add Promises interface

There have been numerous requests for a Promises interface for this module. Adding this interface in addition to the err-back will hopefully simplify the use of this module. The existing API will still be supported but we will use Promises for examples.

  • Define new interface API
  • Add a promises interface alongside the existing API
  • Ensure test coverage
  • Update readme and examples

Node module version out of date

Hi there,
When I try to use this module I get this error:

Uncaught Error: The module '/home/pi/rubiks-robot/node_modules/epoll/build/Release/epoll.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 51. This version of Node.js requires
NODE_MODULE_VERSION 53. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or`npm install`).
    at process.module.(anonymous function) [as dlopen] (ELECTRON_ASAR.js:173:20)
    at Object.Module._extensions..node (module.js:598:18)
    at Object.module.(anonymous function) [as .node] (ELECTRON_ASAR.js:173:20)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at bindings (/home/pi/rubiks-robot/node_modules/bindings/bindings.js:76:44)
    at Object.<anonymous> (/home/pi/rubiks-robot/node_modules/epoll/epoll.js:1:192)

Any idea what this means or how to fix it?

Thanks

Is there a way with the GPIO utility when exporting a pin to DIR OUT, it comes in high value?

Is there a way with the GPIO utility when exporting a pin to DIR OUT, it comes in high value?

I saw that this has been fixed for the rpi-gpio.js library, but with the utility this remains unsolved.

I program my scripts with bash, and use a bank of relays that are fired as soon as I export the pins as out.

The same thing happens if I send by bash the value "out" to the direction file of the pin.

Thanks!

read pin & blocking

Hi, thanks for your very useful library !
I try to listen changes on a specif pin (on input only). It works if I use "gpio.read()" but the script is waiting for action after.. How to solve it ?

My goal is to listen chane but the eventlistener is not working for me :(

thanks for your help !

Error: Cannot find module 'rpi-gpio'

I'm probably overlooking something obvious, but I can't seem to get this code working. Is there a naming issue I'm not seeing?

Installing:

$ npm install -g rpi-gpio

> [email protected] install /home/pi/.npm-packages/lib/node_modules/rpi-gpio/node_modules/epoll
> node-gyp rebuild

make: Entering directory '/home/pi/.npm-packages/lib/node_modules/rpi-gpio/node_modules/epoll/build'
  CXX(target) Release/obj.target/epoll/src/epoll.o
  SOLINK_MODULE(target) Release/obj.target/epoll.node
  COPY Release/epoll.node
make: Leaving directory '/home/pi/.npm-packages/lib/node_modules/rpi-gpio/node_modules/epoll/build'
/home/pi/.npm-packages/lib
└─┬ [email protected] 
  ├── [email protected] 
  ├─┬ [email protected] 
  │ └── [email protected] 
  └─┬ [email protected] 
    ├── [email protected] 
    └── [email protected] 

Using:

$ node
> var gpio = require('rpi-gpio');
Error: Cannot find module 'rpi-gpio'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at repl:1:12
    at sigintHandlersWrap (vm.js:22:35)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInThisContext (vm.js:21:12)
    at REPLServer.defaultEval (repl.js:313:29)
    at bound (domain.js:280:14)
> gpio
undefined
$ node -v
v6.9.1
$ npm -v
3.10.8

Raspberry Pi Zero Works

I use this module for both the Zero and the Zero W without issue. They should be added to the list of supported devices.

Allow Setup to take in an array of channels?

If you look at the python gpio library , setting up a pin is the same as node however the only difference is instead of passing a single channel, we can simply pass an array of channels and it will initialize all and provide the call back.

Python code

chan_list = [11,12]  
GPIO.setup(chan_list, GPIO.OUT)

Meanwhile in node there needs to be a recursive function to ensure all the pins are setup in the correct order and only then can the rest of the execution happen. If this can be below the line it would be very helpful.

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.