Search code examples
javascriptnode.jsraspberry-piraspbianweb-ide

Node.JS onoff not picking up GPIO correctly


I'm building a simple infrared breakbeam circuit to plug into my RPi 2. I have some working code in python that successfully picks up when my infrared beam is broken, but I want to use node.js instead of python.

Here is my python code, nice and simple:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)

try:
        while True:
                print(GPIO.input(7))
                time.sleep(0.01)

except KeyboardInterrupt:
        GPIO.cleanup()

Now I did some reading up on different packages for node.js that let me use GPIO on the Pi and decided that onoff looked like the best one because it works asynchronously with callbacks which I would like to use.

This is the code I'm trying to use for node:

var Gpio = require('onoff').Gpio,
  infrared = new Gpio(7, 'in');
var interval = setInterval(function()
{
   console.log(infrared.readSync() ^ 1); 
}, 100);

function exit() {
  infrared.unexport();
  process.exit();
}

process.on('SIGINT', exit);

The problem is with node I always get the same signal of 0 no matter what I do. I have tried eliminating my circuit as the problem by just using a simple button instead, and even that doesn't work (I tested the same circuit using python and that worked fine).

This isn't even using the asynchronous part of it (which also doesn't work since no interrupt ever happens).

I have tried using GPIO Admin to export the pin I'm using:

pi@counter ~ $ sudo gpio-admin export 7
gpio-admin: failed to change group ownership of /sys/devices/virtual/gpio/gpio7/direction: No such file or directory

/sys/devices/virtual/gpio/ does not exist on my system.

Do I have to do anything specific to get node to play nicely with my GPIO?

Note that I wrote this using Adafruit WebIDE, and yes I have tried executing it out of the context of the IDE and it still doesn't work. I am using the latest stable build of raspbian as of 2015/04/29 with a fully updated system, using nodejs v0.12.2.


Solution

  • The main problem with the node GPIO library is that the params to give is the pin number not the GPIO number...

    Try to use the pin number and normally it will work.

    GPIO 7 is the pin 26 on a raspberry pi