
Raspi Blinking Led in NodeJs
Controlling an LED using a Raspberry Pi and Node.js is super fun and easy with the onoff
library, which gives you GPIO control right from JavaScript!
Hereβs a full guide to blink an LED on a Raspberry Pi using Node.js π
β What You Need
Raspberry Pi (any model with GPIO)
LED
330Ξ© resistor
Breadboard + jumper wires
π§° Circuit Setup
Connect the LED:
Long leg (anode) β GPIO pin (e.g., GPIO17 β Pin 11 on Pi header)
Short leg (cathode) β Resistor β GND (e.g., Pin 6)
π¦ Step 1: Install Node.js on Raspberry Pi
sudo apt updatesudo apt install nodejs npm -y
Check version:
node -vnpm -v
π¦ Step 2: Create Project and Install onoff
mkdir led-blinkcd led-blinknpm init -ynpm install onoff
π‘ Step 3: Create blink.js
const Gpio = require('onoff').Gpio;// Use GPIO17 (pin 11)const led = new Gpio(17, 'out');let isOn = 0;// Blink every 500msconst interval = setInterval(() => { isOn = isOn ^ 1; // toggle 0/1 led.writeSync(isOn);}, 500);// Cleanup on exitprocess.on('SIGINT', () => { clearInterval(interval); led.writeSync(0); // turn LED off led.unexport(); console.log('\nLED Blinking stopped.'); process.exit();});
π Step 4: Run the Code
sudo node blink.js
Use
sudo
to access GPIO pins.
Your LED should now blink every 0.5 seconds! π
π§ Bonus: Control Multiple LEDs or Add a Button?
Want to:
Blink multiple LEDs?
Control via button or web UI?
Build a REST API or dashboard for GPIO?