Async raspberry pi gpio events in nodejs

I connected a button to the Raspberry Pi GPIO ports:

http://adafruit.com/products/801

The pi-gpio node js module allows only to pull the current status but not waiting for a state change:

gpio.read(16, function(err, value) {
    if(err) throw err;
    console.log(value);    // The current state of the pin
});

Is there any solution to bind events asynchronously?

In this example this would be whenever the button is pressed.

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.

I'd suggest using the module called onoff.

It has the ability to watch a value-file while not taxing the cpu with polling in intervals.

I made a small test-app with node.js to try out leds and buttons with it, you can check it out here.

I just came accross this modulle

https://github.com/EnotionZ/GpiO

I have not looked in depth to it but is seems it uses the setInterval method in the background.

As an aside, there is a project very similar to node.js (however much more cut-down) called Espruino.

This runs on Raspberry Pi (and many low power ARMs microcontrollers too), supports HTTP, and has a function called setWatch which behaves in exactly the way you require.