๐Ÿ“ถ Node.js โ€“ WebSocket-Based Controls
Estimated reading: 4 minutes 422 views

Node.js โ€“ RGB LED with WebSocket โ€“ Real-Time RGB Control from Browser


Introduction โ€“ Why Control RGB LED with WebSocket?

An RGB LED combines red, green, and blue lights into a single package to display millions of colors. When controlled via WebSocket in Node.js, you can change its color in real time from a browser or mobile UIโ€”perfect for smart lighting, IoT dashboards, and interactive art.

In this guide, youโ€™ll learn:

  • How to wire and control an RGB LED on Raspberry Pi using Node.js
  • Set up WebSocket communication between Node.js and browser
  • Send RGB values dynamically and update LED colors instantly
  • Use onoff and ws libraries for GPIO and WebSocket handling

Hardware Requirements

Component Description
Raspberry PiAny model with GPIO support
RGB LED (common cathode)Use common cathode type for simplicity
3 x 330ฮฉ ResistorsOne for each RGB pin
Breadboard + WiresFor prototyping

RGB LED Wiring Diagram

  • R (Red) โ†’ GPIO 17 (Pin 11) + Resistor
  • G (Green) โ†’ GPIO 27 (Pin 13) + Resistor
  • B (Blue) โ†’ GPIO 22 (Pin 15) + Resistor
  • Common Cathode (-) โ†’ GND (Pin 6)

Use 330ฮฉ resistors on each RGB line to avoid overcurrent.


Install Node.js Packages

npm install onoff ws express

Backend โ€“ Node.js WebSocket RGB Control

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const Gpio = require('onoff').Gpio;

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

const red = new Gpio(17, 'out');
const green = new Gpio(27, 'out');
const blue = new Gpio(22, 'out');

// Serve HTML UI
app.use(express.static(__dirname + '/public'));

// Handle incoming WebSocket RGB commands
wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    const { r, g, b } = JSON.parse(message);

    red.writeSync(r ? 1 : 0);
    green.writeSync(g ? 1 : 0);
    blue.writeSync(b ? 1 : 0);

    console.log(` Color updated: R:${r}, G:${g}, B:${b}`);
  });
});

// Cleanup on exit
process.on('SIGINT', () => {
  red.writeSync(0); red.unexport();
  green.writeSync(0); green.unexport();
  blue.writeSync(0); blue.unexport();
  console.log(' Cleanup complete.');
  process.exit();
});

server.listen(3000, () => console.log(' Server running at http://localhost:3000'));

Frontend โ€“ public/index.html

<!DOCTYPE html>
<html>
<head>
  <title>RGB Control</title>
</head>
<body>
  <h2> RGB LED Controller</h2>
  <label><input type="checkbox" id="r"> Red</label><br>
  <label><input type="checkbox" id="g"> Green</label><br>
  <label><input type="checkbox" id="b"> Blue</label><br>

  <script>
    const ws = new WebSocket('ws://' + location.host);
    const sendColor = () => {
      const data = {
        r: document.getElementById('r').checked,
        g: document.getElementById('g').checked,
        b: document.getElementById('b').checked
      };
      ws.send(JSON.stringify(data));
    };

    ['r', 'g', 'b'].forEach(id =>
      document.getElementById(id).addEventListener('change', sendColor)
    );
  </script>
</body>
</html>

Output โ€“ What Youโ€™ll See

  • Visit http://<pi-ip>:3000 in your browser
  • Toggle checkboxes to turn RED, GREEN, and BLUE on/off
  • LED color updates in real time based on checkbox states

Example:

  • Red + Green = Yellow
  • Red + Blue = Magenta
  • All ON = White

Best Practices for RGB with WebSocket

Practice Why Itโ€™s Useful
Use JSON.parse() safelyAvoids crashing on malformed WebSocket input
Add debounce logic (optional)Prevents flickering on rapid checkbox changes
Use PWM (future upgrade)For smooth brightness and color mixing
Always clean up GPIO on exitFrees hardware resources
Run server with sudo (if needed)GPIO might require root permissions

Summary โ€“ Recap & Next Steps

Using WebSocket with Node.js and Raspberry Pi, you built a real-time, browser-controlled RGB LED system. This project combines frontend interactivity with hardware control, ideal for home automation and IoT.

Key Takeaways:

  • Use onoff for GPIO, ws for real-time WebSocket connections
  • Control RGB LED states via JSON messages from the browser
  • Sync UI events to GPIO output in real time
  • Easily extendable to mobile, touch panels, or sensors

Real-world relevance:
Used in smart lighting systems, interactive art, status indicators, and real-time dashboard interfaces.


FAQs โ€“ Node.js RGB LED WebSocket Control


Can I control RGB brightness with this setup?
Not with digital pins alone. Youโ€™ll need PWM control using pigpio instead of onoff.


How do I access this from my phone?
Use your Raspberry Piโ€™s local IP, like http://192.168.1.10:3000 over Wi-Fi.


What happens if I check all three boxes?
The RGB LED emits white light (Red + Green + Blue = White).


Can I use sliders for finer color control?
Yes! Add range inputs for R, G, and B (0โ€“255) and use PWM to set brightness levels.


How do I turn off the LED completely?
Uncheck all boxes. The GPIO writes 0 to each pin, turning the LED off.


Share Now :
Share

๐ŸŒˆ Node.js โ€“ RGB LED with WebSocket

Or Copy Link

CONTENTS
Scroll to Top