Node.js Raspberry Pi GPIO LED and Pushbutton

Here is a complete, beginner-friendly and practical guide for Node.js Raspberry Pi GPIO LED and Pushbutton.


Node.js Raspberry Pi – LED with Pushbutton (GPIO Input + Output)

In this project:

  • You press a button → the LED turns ON

  • Release the button → LED turns OFF

This teaches both GPIO input and GPIO output using Node.js.


1. What You Need

Hardware:

  • 1 × Raspberry Pi (any GPIO model)

  • 1 × LED

  • 1 × 330Ω resistor

  • 1 × Pushbutton

  • Jumper wires

  • Breadboard (optional)


🔌 2. Wiring Diagram

LED:

  • GPIO17 → Resistor → LED → GND

Button:

Use a pull-down circuit.

  • One side of the button → GPIO4

  • Same side → 10kΩ pull-downGND

  • Other side → 3.3V

Simplified:

3.3V ----[BUTTON]---- GPIO4
|
10kΩ
|
GND

Button Press → GPIO4 gets HIGH (1)
Button Released → GPIO4 stays LOW (0)


📦 3. Install Required Library

npm install onoff

💡 4. Create File

nano led_button.js

🧩 5. Node.js Code: LED with Pushbutton


 


6. Run the Program

sudo node led_button.js

Now:

  • Press Button → LED ON

  • Release Button → LED OFF

🎉 You now have your first interactive Raspberry Pi project using Node.js!


🧠 How It Works

ComponentPurpose
Gpio(17, “out”)LED as output
Gpio(4, “in”, “both”)Detect button press/release
button.watch()Event listener for state change
led.writeSync(value)Sets LED ON/OFF

🛠️ Optional Enhancements

✔ Debounce the button (avoid multiple triggers)

✔ Toggle LED on each press (instead of holding)


 

✔ Control LED brightness using PWM with pigpio

You may also like...