๐Ÿ“ถ Node.js โ€“ WebSocket-Based Controls
Estimated reading: 4 minutes 19 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

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

Or Copy Link

CONTENTS
Scroll to Top