ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Raspi Led And Pushbutton in NodeJs

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='22' AND `tutorial_submenu`='1413' AND `tutorial_status`=1 LIMIT 1

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

ComponentPurpose
1 x LEDOutput device
1 x 330Ω resistorProtect LED
1 x PushbuttonInput trigger
Breadboard + jumper wiresFor wiring
Raspberry PiAny model with GPIO


🧠 Circuit Wiring

ComponentConnect To
LED (long leg)GPIO17 (Pin 11)
LED (short leg) → resistor → GNDPin 6
Button Side 1GPIO27 (Pin 13)
Button Side 2GND (Pin 6)

Optional: Use a pull-down resistor (or enable internal one via Node.js)


📦 Install Dependencies

bash

npm init -ynpm install onoff


💻 Code: button-led.js

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

bash

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

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql