
Raspi Led And Pushbutton in NodeJs
Combining an LED and a pushbutton on a Raspberry Pi using Node.js is a great beginner project that teaches you both GPIO input and GPIO output — in JavaScript! 🚀
✅ Goal
🔘 Press the button → 💡 Turn on the LED
🧰 What You Need
Component | Purpose |
---|---|
1 x LED | Output device |
1 x 330Ω resistor | Protect LED |
1 x Pushbutton | Input trigger |
Breadboard + jumper wires | For wiring |
Raspberry Pi | Any model with GPIO |
🧠 Circuit Wiring
Component | Connect To |
---|---|
LED (long leg) | GPIO17 (Pin 11) |
LED (short leg) → resistor → GND | Pin 6 |
Button Side 1 | GPIO27 (Pin 13) |
Button Side 2 | GND (Pin 6) |
Optional: Use a pull-down resistor (or enable internal one via Node.js)
📦 Install Dependencies
npm init -ynpm install onoff
💻 Code: button-led.js
const led = new Gpio(17, 'out');// Setup GPIO27 as input for Button, trigger on both press and releaseconst button = new Gpio(27, 'in', 'both');// Watch for button state changesbutton.watch((err, value) => { if (err) { console.error('Error:', err); return; } led.writeSync(value); // If pressed (1), LED on. If released (0), LED off. console.log('Button state:', value ? 'Pressed' : 'Released');});// Graceful exitprocess.on('SIGINT', () => { led.writeSync(0); led.unexport(); button.unexport(); console.log('\nStopped. GPIO cleaned up.'); process.exit();});
🚀 Run the Program
sudo node button-led.js
🔘 When you press the button, the LED turns on
🔁 When you release it, the LED turns off
🔧 Want to Expand?
You can:
Toggle the LED (instead of momentary)
Add debounce to prevent bouncing
Control via web page (
express
,socket.io
)Add more LEDs or use a relay to control real devices