Note that for simplicity, further examples do not include error checking. You should always check for errors.
Promises and callbacks
Most functions are asynchronous, returning immediately and delivering result later via callbacks.
Two approaches are possible: using node-style callbacks and using promises.
To use promises, omit the last callback argument – and a promise will be returned.
By default, bluebird is used for promises.
See below for information about using other promise implementations
var gpio =require('linux-gpio');
gpio.export(266,{direction:gpio.DIR_OUT})
.then(function(pin){
console.log("Exported pin %d",pin.pin);
})
.catch(function(err){
console.error(err);
})
.finally(function(){
gpio.close();
});
Exporting GPIO pin
Before using a GPIO pin, it must be first exported by writing pin number to /sys/class/gpio/export.
This creates /sys/class/gpioXXX/ directory with some files inside used to control the pin.
Use gpio.export() function:
Second argument to export() is an object used to specify options such as pin I/O direction, interrupt mode and invert mode.
All keys are optional. If a key is not specified, corresponding option is not changed
After you are done with GPIO, call close() to stop event loop used for interrupt handling. Otherwise, your program will not exit when you expect it to do so
Changing pin direction
var gpio =require('linux-gpio');
gpio.export(266,{},function(err,pin){
console.log("Exported pin %d",pin.pin);
pin.direction(gpio.DIR_OUT,function(err){
console.log("Pin %d configured as output",pin.pin);
pin.direction(gpio.DIR_IN,function(err){
console.log("Pin %d configured as input",pin.pin);
gpio.close();
});
});
});
Use gpio.DIR_OUT for output, gpio.DIR_IN for input
I/O direction can also be specified using direction option for gpio.export() call.
Reading pin direction
var gpio =require('linux-gpio');
gpio.export(266,{},function(err,pin){
console.log("Exported pin %d",pin.pin);
pin.direction(function(err,dir){
console.log("Pin %d configured as %s",pin.pin, dir);
gpio.close();
});
});
Changing pin invert mode
var gpio =require('linux-gpio');
gpio.export(266,{},function(err,pin){
console.log("Exported pin %d",pin.pin);
pin.invert(true,function(err){
console.log("Pin %d is in inverted mode",pin.pin);
pin.invert(false,function(err){
console.log("Pin %d is in non-inverted mode",pin.pin);
gpio.close();
});
});
});
Inverted mode can also be specified using invert option for gpio.export() call.
console.log("Pin %d interrupt mode set to \"both\"",pin.pin);
gpio.close();
});
});
Use one of gpio.EDGE_NONE, gpio.EDGE_RISING, gpio.EDGE_FALLING and gpio.EDGE_BOTH. gpio.EDGE_NONE disables interrupt.
Interrupt mode can also be specified using edge option for gpio.export() call.
Interrupt mode can be only specified for pins configured as inputs. Not all GPIO pins can generate interrupts, even if configured as input. Refer to yor system's documentation to find out which pins are interrupt-enabled.