Welcome to The Coding College! In this tutorial, we’ll explore how to control and interact with GPIO (General-Purpose Input/Output) pins on a Raspberry Pi using Node.js. GPIO pins are the backbone of hardware projects with Raspberry Pi, allowing it to interact with external devices like LEDs, buttons, sensors, and motors.
What Are GPIO Pins?
GPIO pins are programmable pins on the Raspberry Pi used to interface with external hardware. These pins can act as:
- Inputs: To read signals from sensors or buttons.
- Outputs: To send signals to devices like LEDs or relays.
Why Use Node.js for GPIO?
- Asynchronous I/O: Node.js handles real-time interactions smoothly.
- Ease of Use: JavaScript’s simplicity makes coding hardware projects easier.
- Rich Libraries: Libraries like
onoff
andrpi-gpio
simplify GPIO operations.
GPIO Pin Layout
Raspberry Pi models have a 40-pin GPIO header. Some important pins include:
- 3.3V and 5V: Power supply.
- GND (Ground): Common ground.
- GPIO Pins: Programmable pins for input/output.
Refer to the official GPIO Pinout Diagram for your Raspberry Pi model.
Setting Up Node.js for GPIO
Step 1: Install Node.js
Follow the steps in our Node.js and Raspberry Pi Guide to install Node.js.
Step 2: Install a GPIO Library
Install the onoff
library for GPIO control:
npm install onoff
Example: Blink an LED
Let’s create a simple project to blink an LED connected to a GPIO pin.
Hardware Setup
- Connect the LED:
- Positive (longer leg): Connect to GPIO17 (Pin 11).
- Negative (shorter leg): Connect to GND (Pin 6) via a resistor.
Code Example
Create a file named blink.js
and add the following code:
const Gpio = require('onoff').Gpio;
// Initialize GPIO17 as output
const led = new Gpio(17, 'out');
// Blink the LED every second
let isOn = false;
setInterval(() => {
isOn = !isOn;
led.writeSync(isOn ? 1 : 0); // Toggle LED state
}, 1000);
// Graceful shutdown
process.on('SIGINT', () => {
led.writeSync(0); // Turn off LED
led.unexport(); // Free resources
console.log('Exiting...');
process.exit();
});
Run the Script
Run the script with sudo
to access GPIO:
sudo node blink.js
The LED should start blinking at one-second intervals.
Example: Read a Button Press
Add a button to the setup and detect its presses.
Hardware Setup
- Button Wiring:
- One terminal: Connect to GPIO27 (Pin 13).
- Other terminal: Connect to GND (Pin 6).
Code Example
const Gpio = require('onoff').Gpio;
// Initialize GPIO27 as input
const button = new Gpio(27, 'in', 'both');
// Watch for button presses
button.watch((err, value) => {
if (err) {
console.error('Error reading button:', err.message);
return;
}
console.log('Button state:', value ? 'Pressed' : 'Released');
});
// Graceful shutdown
process.on('SIGINT', () => {
button.unexport(); // Free resources
console.log('Exiting...');
process.exit();
});
Run the Script
sudo node button.js
Pressing the button will log its state to the console.
Advanced GPIO Operations
- PWM (Pulse Width Modulation): Control motor speed or LED brightness.
- SPI/I2C Communication: Interact with advanced devices like sensors or displays.
- GPIO Debouncing: Handle button press noise using software debouncing.
Best Practices
- Use Resistors: Protect GPIO pins with appropriate resistors.
- Shutdown Gracefully: Ensure GPIO pins are released properly.
- Power Safety: Avoid drawing excessive current through GPIO pins.
Conclusion
Using Node.js to control GPIO on a Raspberry Pi opens up a world of hardware possibilities. Whether you’re building simple LED circuits or complex IoT devices, Node.js makes it accessible and efficient.
For more coding and hardware tutorials, visit The Coding College.