Async raspberry pi gpio events in nodejs

后端 未结 4 1320
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 00:09

I connected a button to the Raspberry Pi GPIO ports:

\"http://adafruit.com/products/801\"

The pi-gpio node

4条回答
  •  感情败类
    2021-02-04 00:42

    unfortunately there is no event generated when using the hardware GPIO. You can create an event by using an emitter and setInterval to create a timer that checks the status every so often and then emits an event out to your application.

    var ee = new process.EventEmitter(),
        buttonState;
    
    ee.on('stateChange', function(previousValue, value){
      console.log('button state changed from', previousValue, 'to', value);
    });
    
    setInterval(function(){
      gpio.read(16, function(err, value) {
        if(err){
          ee.emit('error', err);
        } else{
          if(buttonState !== value){
            var previousState = buttonState;
            buttonState = value;
            ee.emit('stateChange', previousState, value);
          }
        }        
      });
    }, 50); //check button state every 50ms
    

    You can tune the timer to your requirements. I think 50ms is a good number as it is not possible for the human eye to detect the difference if it is faster.

提交回复
热议问题