The Raspberry Pi is a series of low-cost, programmable computers that include a set of GPIO, or 'General Purpose Input Output', pins that can be used to connect and control external electronic devices, and to create Internet of Things (IoT) solutions.
The exact number and role of the pins changes between individual models but is generally divided into power, ground, and general-purpose pins. The power and ground pins are not programmable. The power pin supplies a constant 3.3V/5V power to the circuit while the ground pin is used to connect to the cathode of the circuit.
The general-purpose pins are fully programmable and can be used in either an output or input mode. When set to output mode, the pins provide a constant 3.3V power that can be turned on or off. When set to input mode, the pin reads the current supplied by the circuit and returns a Boolean value indicating if it receives 3.3V power or not.
Of course, these capabilities aren't new and have been widely available to developers through microcontrollers such as Arduino or NodeMCU. However, these devices generally came with limited memory and computing power and required the use of particular programming languages.
The Raspberry Pi, on the other hand, supports a more robust CPU that is capable of running Linux and supports NodeJS, allowing JavaScript developers to use their existing skillset and build sophisticated devices with relative ease.
To interact with the GPIO pins, we use a NodeJS module called onoff that provides simple access to the individual pins.
The equivalent of a 'hello world' demo in the world of microcontrollers is a blinking led. Most of the code in the example below should already be familiar to JavaScript developers.
const Gpio = require('../onoff').Gpio;
const led = new Gpio(17, 'out');
After requiring the module, we define the roles of the pins we wish to interact with. The number identifies the pin on the board, followed by determining if the pin is used to read ('in') or write ('out').
In this example, we defined a pin called led, assigned it to physical pin 17 and set it to write mode ('out')
const blinkInterval = setInterval(blinkLED, 500);
function blinkLED() {
if (led.readSync() === 0) {
led.writeSync(1);
} else {
led.writeSync(0);
}
}
Now all that's left is to make our led blink by creating a 500ms interval and turning the led on/off based on its current state.
setTimeout(() => {
clearInterval(blinkInterval);
led.writeSync(0);
led.unexport();
}, 5000);
Assuming we do not wish to continue blinking the LED indefinitely, we would also need to clean up at the end. In this example, we will wait 5 seconds before clearing our interval, turning off the led, and releasing its resource.
Of course, the Raspberry Pi can do more than just blinking LEDs. Developers have built anything from drones to Raspberry Pi skateboards. While not specifically written for JavaScript, you can find many ideas for exciting projects of all levels at the Raspberry Pi website