JamesBarwell / rpi-gpio.js

Control Raspberry Pi GPIO pins with node.js
MIT License
657 stars 116 forks source link

Module works in Node shell but not through code #72

Closed omkarkhair closed 6 years ago

omkarkhair commented 6 years ago

It seems like I am doing something wrong here, but I'm unable to figure out what due to the nature of the problem.

I've setup my Raspberry Pi 2 Model B v1.1 with Node.js v8.7 and installed rpi-gpio.

I used Node shell (REPL) to test the module, and it worked like a charm. But when I put the same 3 lines of code in app.js and try a node app.js I get the following error. Code added below for reference.

Error:

/home/pi/PiClient/node_modules/rpi-gpio/rpi-gpio.js:358
        return currentPins[channel] + '';
                          ^

TypeError: Cannot read property '7' of undefined
    at getPinRpi (/home/pi/PiClient/node_modules/rpi-gpio/rpi-gpio.js:358:27)
    at Gpio.read.input (/home/pi/PiClient/node_modules/rpi-gpio/rpi-gpio.js:266:19)
    at Object.<anonymous> (/home/pi/PiClient/test.js:5:6)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Function.Module.runMain (module.js:665:10)
    at startup (bootstrap_node.js:187:16)

Code:

var gpio = require('rpi-gpio');
gpio.(7, gpio.DIR_IN);
gpio.read(7, function (err, val) {
   console.log(err, val);
});

Any help is appreciated. I'm investigating what difference the Node shell environment makes that things just work.

JamesBarwell commented 6 years ago

Is your line 2 incorrect? Surely it should be gpio.setup(7, gpio.DIR_IN);

The reason it's working in the shell and not as a program is that in the shell you have a big delay between you entering each line input, and that delay is allowing the function you're running to complete. In code, everything will run as quickly as it can. You haven't set your code up to be asynchronous so your (presumed) setup function is immediately followed by the read, before it completes.

Compare your solution to the first example of reading a pin in the readme. You'll notice that in the example, it passes a callback readInput, and that callback isn't triggered until setup completes.

omkarkhair commented 6 years ago

That was it. Damn do I feel stupid now. I thought of the setup callback as optional.