
Raspi Gpio Introduction in NodeJs
Here's a beginner-friendly intro to using GPIO pins on a Raspberry Pi with Node.js β perfect if you want to control hardware like LEDs, buttons, sensors, and more using JavaScript! π
π§ What is GPIO?
GPIO stands for General Purpose Input/Output.
Raspberry Piβs GPIO pins allow you to send output (e.g. turn on an LED) or read input (e.g. check if a button is pressed).
GPIO Pin Example | Function |
---|---|
GPIO17 (pin 11) | Digital Output |
GPIO27 (pin 13) | Digital Input |
β Node.js + GPIO = JavaScript Hardware Control
To interact with GPIO pins in Node.js, the most popular libraries are:
onoff
β simple GPIO read/writerpi-gpio
β similar, slightly olderpigpio
β for precise PWM, servo, ultrasonic sensors, etc.
βοΈ Basic Circuit Example
Letβs start with a basic setup:
Hardware:
LED connected to GPIO17 (Pin 11)
330Ξ© resistor
GND (Pin 6)
π¦ Step 1: Install Dependencies
npm init -ynpm install onoff
π‘ Step 2: Blink an LED (GPIO Output)
const Gpio = require('onoff').Gpio;const led = new Gpio(17, 'out'); // GPIO17setInterval(() => { led.writeSync(led.readSync() ^ 1); // Toggle LED}, 500);// Cleanup on Ctrl+Cprocess.on('SIGINT', () => { led.writeSync(0); led.unexport(); console.log('LED turned off'); process.exit();});
Run with:
sudo node led-blink.js
π Step 3: Read a Button (GPIO Input)
Wire a push button to GPIO27 (Pin 13) and GND (Pin 6).
// button.jsconst Gpio = require('onoff').Gpio;const button = new Gpio(27, 'in', 'both');button.watch((err, value) => { if (err) throw err; console.log('Button state:', value);});process.on('SIGINT', () => { button.unexport(); console.log('Button program stopped'); process.exit();});
π§ GPIO Modes
'out'
β output (LEDs, relays, etc.)'in'
β input (buttons, switches, etc.)'both'
β detect rising and falling edges (good for buttons)
π¨ Safety Tips
Always use resistors to limit current.
Donβt connect high-voltage devices directly.
GPIO pins are 3.3V β sending 5V can damage your Pi.
π Whatβs Next?
You can build cool stuff like:
LED chasers / flowing lights
Motion sensors
Web-controlled relays
Real-time dashboards with
Express
orSocket.io