简体   繁体   中英

How do I get status of GPIO pin on load using raspberry pi node js?

I am using a raspberry pi and I have loaded node.js, and socket.io. I am able to see when a switch is changed on pin 18. What I would like to know is how do I get the status of a switch when the webpage is first loaded.

In my app.js I have

var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
var pushButton = new Gpio(18, 'in', 'both'); //use GPIO pin 18 as input, and 'both' button presses, and releases should be handled


io.sockets.on('connection', function (socket) {// WebSocket Connection
console.log("gpio status pin : ", pushButton);
  var lightvalue = 0;
  pushButton.watch(function (err, value) { //Watch for hardware interrupts on pushButton
if (err) { //if an error
  console.error('There was an error', err); //output error message to console
  return;
}
lightvalue = value;
socket.emit('light', lightvalue); //send button status to client
  });
socket.on('light', function(data){
console.log("data: ", data);
  });

});

I have tried many steps and the closet thing I can see if the read buffer changes from 30 to 31. This is printed from the pushbutton. Can I use this?

gpio status pin : Gpio { _gpio: 18, _gpioPath: '/sys/class/gpio/gpio18/', _debounceTimeout: 0, _readBuffer: , _listeners: [ [Function] ], _valueFd: 13, _risingEnabled: true, _fallingEnabled: true, _poller: Epoll { closed: false } }

After looking everywhere, I found it was in front of my face the whole time.

pushButton.readSync() does give me the correct high/low value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM