JamesBarwell / rpi-gpio.js

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

Calling a read function from another module #29

Closed brunno-oliveira closed 8 years ago

brunno-oliveira commented 8 years ago

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 ?

JamesBarwell commented 8 years ago

In the first block of code, gpio.setup is going to run instantly as soon as the module is loaded. As you say, inGpio hasn't been defined at that point, so it's going to error. Looks like you need to restructure your code so that setup is only run when read.readInput gets called.

Maybe something more like this (modified from the README example):

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

module.exports = function(inGpio) {
  gpio.setup(inGpio, gpio.DIR_IN, readInput);

  function readInput() {
      gpio.read(inGpio, function(err, value) {
          console.log('The value is ' + value);
      });
  }
}
brunno-oliveira commented 8 years ago

It works!! Thanks for helping, I'm new to Node.sj. I just started using it for AWS SDK.

JamesBarwell commented 8 years ago

Good stuff. Cheers.