Node.js Raspberry Pi GPIO Introduction

Here is a clean, simple, and complete guide for Node.js Raspberry Pi GPIO Introduction.


🍓 Node.js Raspberry Pi GPIO Introduction

Raspberry Pi boards come with 40 GPIO (General Purpose Input/Output) pins that allow you to interact with external electronics such as:

  • LEDs

  • Buttons

  • Sensors

  • Relays

  • Motors

  • Displays

With Node.js, you can easily control these GPIO pins using JavaScript, making it perfect for IoT and automation.


⭐ Why Use Node.js for Raspberry Pi GPIO?

✔ Non-blocking, event-driven architecture
✔ Perfect for real-time hardware tasks
✔ Huge ecosystem (npm packages)
✔ Easy to build web dashboards + hardware control
✔ Ideal for IoT, robotics, and home automation


🧩 GPIO Pin Types on Raspberry Pi

Raspberry Pi provides:

🔹 GPIO pins (input/output)

🔹 3.3V power pins

🔹 5V power pins

🔹 Ground pins

🔹 Special pins like I2C, SPI, UART

Important: GPIO pins operate at 3.3V, NOT 5V.


📦 Popular Node.js GPIO Libraries

LibraryBest ForNotes
onoffBasic GPIOSimple, widely used
rpi-gpioBeginner friendlyEasy API
pigpioAdvanced controlPWM, servo control, fast timing

Most commonly used: onoff


📌 Installing GPIO Library

npm install onoff

🔌 Basic GPIO Setup with Node.js

GPIO pins have two modes:

  • "out" → output (LED, relay)

  • "in" → input (button, sensor)


💡 Example 1: Blink an LED (GPIO Output)

Hardware

  • LED connected to GPIO 17

  • Add a 330Ω resistor in series

Code

const { Gpio } = require("onoff");
const led = new Gpio(17, "out");

setInterval(() => {
led.writeSync(led.readSync() ^ 1); // toggle LED
}, 500);

Run:

sudo node blink.js

🎛️ Example 2: Read a Button (GPIO Input)

Hardware

  • Button connected to GPIO 4

  • Use pull-down resistor

Code:

const { Gpio } = require("onoff");
const button = new Gpio(4, "in", "both");

button.watch((err, value) => {
if (err) throw err;
console.log("Button state:", value);
});


🌐 Example 3: Control GPIO from a Browser

You can turn an LED ON/OFF using Node.js + Express.

const express = require("express");
const { Gpio } = require("onoff");

const led = new Gpio(17, "out");
const app = express();

app.get("/on", (req, res) => {
led.writeSync(1);
res.send("LED is ON");
});

app.get("/off", (req, res) => {
led.writeSync(0);
res.send("LED is OFF");
});

app.listen(3000, () => console.log("Server started"));

Now visit:

http://<raspberry-pi-ip>:3000/on
http://<raspberry-pi-ip>:3000/off

⚙ GPIO Modes & Events

Modes:

  • "in" → read signals

  • "out" → send signals

  • "high" → initial high voltage

  • "low" → initial low voltage

Input edge detection:

  • "rising" → low → high

  • "falling" → high → low

  • "both" → detect any change


🧠 Best Practices

✔ Use external resistors
✔ Avoid 5V devices directly
✔ Stop your app before rewiring
✔ Use led.unexport() when exiting
✔ Prefer pigpio for fast or PWM-based projects

You may also like...