JamesBarwell / rpi-gpio.js

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

Read pin always return true value #76

Closed aderbas closed 6 years ago

aderbas commented 6 years ago

I made a simple rest api and I trigger a relay, it's working okay. But when I go to check the state of the pin, it is always returned true. This is may code for write and read value:

...
// write
gpio.setup(pin, gpio.DIR_HIGH, function(){
  gpio.write(pin, (value==0)?false:true, function(err){
    if(err){
      reject({error: 'Writing error :: pin: '+pin});
    }else{
      resolve({pin: pin, value: value});
    }
  });
});
// read
gpio.setup(pin, gpio.DIR_IN, function(){
  gpio.read(pin, function(err, value){
    if(err){
      reject({error: 'Read error :: pin value'});
    }else{
      resolve({pin: pin, value: value});
    } 
  });  
});
...

My test: localhost:3000/api/pin/7/0 <--- turn off relay, OK localhost:3000/api/pin/7 <--- return true

aderbas commented 6 years ago

gpio.setup(pin, gpio.DIR_IN, .... set value to 1. I see in /sys/class/gpio/gpio4/value that value is 1 always "setup()" is called. What am I doing wrong?

JamesBarwell commented 6 years ago

Just a guess, but I wonder if it could be because the pin is being set up multiple times. It might be worth restructuring the code a bit so that setup only gets called once if it hasn't been called before. I can't remember what the normal behaviour is when it's called multiple times, but I note also that you're not checking for errors coming from the setup callback - perhaps it is silently erroring when you do the read.

By the way, just to simplify further, (value==0)?false:true should not be necessary as the the method already handles this.

aderbas commented 6 years ago

Yeah, I suspected it would be setup multiple times. I will have to do the setup whenever the pin is not installed yet. I'll answer when to fix my code. Yes, I removed (value==0)?false:true =)

aderbas commented 6 years ago

I created a route in API to export the pin before reading/writing. Problem solved for now. Thank you.

JamesBarwell commented 6 years ago

Great, cheers for confirming that that was the problem.

I had a look at the code again. If setup is called twice on the same pin then it will unexport it before the second export. In hindsight perhaps it should error in this case to make these cases easier to spot.