Search code examples
node.jslinuxgpio

npm gpio wrong initialized gpio pin value


I am using this gpio library to read the values of gpio pins. This is the code I use to initialize and read gpio pins:

var gpio38 = gpio.export(38, {

    direction: gpio.DIRECTION.IN,
    interval: 200

});

gpio38.on("change", function(val) { 

    if(val == 1)
        console.log("high") 
    else {
        console.log("low")
    }

});

console.log(gpio38.value); //this is where the problem is

As you can see from the code, the gpio pins are set to inputs and will change according to a physical switch. The change function works perfectly and will print high when the switch is on and off when it is turned off.

The problem I am having is that when I try to print the value of gpio38 right after initialization when I leave the switch on, it will always read 0 even though the value of the value of the that gpio pin is 1 (confirmed by reading the voltage of the pin and the Linux file system).

How can I read the correct value of the pin?


Solution

  • To solve this problem, I ended up going outside the library and used Linux commands in my code to ensure the GPIO pins were exported. I also read the value file of the exported GPIO file on the initial start to see the value and then let the library do work in the pin value changes:

    exec('echo 38 > /sys/class/gpio/export');
    exec('echo 36 > /sys/class/gpio/export');
    
    var pin38_value = parseInt(fs.readFileSync('/sys/class/gpio/gpio38/value', 'utf8'));
    var pin36_value = parseInt(fs.readFileSync('/sys/class/gpio/gpio36/value', 'utf8'));