Introduction
This plain JavaScript module is generic and only rely on system's sysfs.
Please consider other (more mature) gpio libraries out there which support better your hardware,
For instance, of you're looking for a reliable way to communicate with the Raspberry Pi using JavaScript,
check out the wiring-pi JavaScript library.
It provides direct bindings to the fully-featured Wiring Pi C library.
But if you want/need a generic lightweight module, this one can be used as fallback.
Support
Following hardware was reported to work (with some limitations or workarounds)
- ARTIK10 (inputs' pull down resistors are enabled by default)
- Raspberry Pi (use wiringpi's /usr/bin/gpio to change mode: gpio -g mode 11 up)
Installation
Get node.js for your SBC,
If using Debian or deviates (Raspbian for RPi), you can simply run:
sudo apt-get install nodejs
otherwise, install from node or compile it
Usage
This library is an npm package, just define "gpio" in your package.json dependencies or
npm install gpio
Note: you must be have proper privileges to access the GPIO headers (or run node as root).
Standard setup
var gpio = require("gpio");
var gpio4 = gpio.export(4, {
direction: gpio.DIRECTION.OUT,
interval: 200,
ready: function() {
}
});
If you plan to set the header voltage externally, use direction in
and read value from your program.
var gpio = require("gpio");
var gpio4 = gpio.export(4, {
direction: gpio.DIRECTION.IN,
ready: function() {
}
});
API Methods
gpio4.set();
gpio4.set(0);
gpio4.set(function() {
console.log(gpio4.value);
});
gpio4.set(0, function() {
console.log(gpio4.value);
});
gpio4.unexport();
EventEmitter
This library uses node's EventEmitter which allows you to watch
for value changes and fire a callback.
gpio4.on("change", function(val) {
console.log(val)
});
var processPin4 = function(val) { console.log(val); };
gpio4.on("change", processPin4);
gpio4.removeListener("change", processPin4);
gpio4.removeAllListeners("change");
gpio4.setDirection(gpio.DIRECTION.OUT);
gpio4.setDirection(gpio.DIRECTION.IN);
Example
Cycle voltage every half a second
var gpio = require("gpio");
var gpio22, gpio4, intervalTimer;
gpio22 = gpio.export(22, {
ready: function() {
intervalTimer = setInterval(function() {
gpio22.set();
setTimeout(function() { gpio22.reset(); }, 500);
}, 1000);
}
});
gpio4 = gpio.export(4, {
ready: function() {
gpio22.on("change", function(val) {
gpio4.set(1 - val);
});
}
});
setTimeout(function() {
clearInterval(intervalTimer);
gpio22.removeAllListeners('change');
gpio22.reset();
gpio22.unexport();
gpio4.reset();
gpio4.unexport(function() {
process.exit();
});
}, 10000)
References
Demos on Raspberry Pi: