Node.js Raspberry Pi RGB LED with WebSocket

Below is a complete and easy Node.js + Raspberry Pi WebSocket RGB LED Controller guide.
You will build a real-time RGB LED controller using WebSockets, allowing you to adjust Red, Green, and Blue intensities instantly from a webpage.


🎨 Node.js Raspberry Pi RGB LED Control with WebSocket

This project will let you:

✔ Control RGB LED colors in real-time
✔ Use PWM to adjust brightness
✔ Communicate instantly via WebSocket
✔ Build a simple UI with sliders


🔧 1. Hardware Requirements

RGB LED Pins (Common Cathode recommended):

  • Red → GPIO17

  • Green → GPIO27

  • Blue → GPIO22

  • GND → Resistor → LED Ground

Circuit:

GPIO17 --- 330Ω --- R (Red)
GPIO27 --- 330Ω --- G (Green)
GPIO22 --- 330Ω --- B (Blue)
GND ---------------- Common Ground

🧩 2. Install Required Packages

mkdir rgb-websocket
cd rgb-websocket
npm install express ws pigpio

We use:

  • express → serve webpage

  • ws → WebSocket

  • pigpio → PWM for RGB LEDs


📄 3. Create Server Script

Create file:

nano server.js

Paste this code:


 

Save & exit: CTRL + X → Y → Enter


🎛️ 4. Create Web UI

Create HTML file

nano index.html

Paste:

<!DOCTYPE html>
<html>
<head>
<title>RGB LED WebSocket Control</title>
<style>
body { font-family: Arial; text-align: center; padding-top: 40px; }
.slider { width: 300px; }
h2 { margin-bottom: 5px; }
</style>
</head>
<body>
<h1>Raspberry Pi RGB LED Control</h1><h2>Red</h2>
<input id=“r” class=“slider” type=“range” min=“0” max=“255” oninput=“updateColor()”>

<h2>Green</h2>
<input id=“g” class=“slider” type=“range” min=“0” max=“255” oninput=“updateColor()”>

<h2>Blue</h2>
<input id=“b” class=“slider” type=“range” min=“0” max=“255” oninput=“updateColor()”>

<h3 id=“status”></h3>

<script>
const ws = new WebSocket(“ws://” + window.location.host);

ws.onmessage = (msg) => {
document.getElementById(“status”).innerText = msg.data;
};

function updateColor() {
const r = document.getElementById(“r”).value;
const g = document.getElementById(“g”).value;
const b = document.getElementById(“b”).value;

ws.send(JSON.stringify({ r, g, b }));
}
</script>

</body>
</html>

Save & exit.


🚀 5. Start the WebSocket RGB Server

sudo node server.js

Output:

RGB WebSocket Server running at http://localhost:3000

🌐 6. Open the Web Controller

On any device in same network:

👉 http://<raspberry-pi-ip>:3000

Example:

http://192.168.1.25:3000

Move sliders → LED color updates instantly (no page refresh!).

You may also like...