nodejs
  1. nodejs-raspi-rgb-led-websocket

Node.js Raspberry Pi RGB LED WebSocket

In this tutorial, we will build a basic Node.js application running on a Raspberry Pi that will allow us to control an RGB LED using a web interface that communicates using WebSocket protocol.

Prerequisites

  • Raspberry Pi running Raspbian with Node.js and npm installed.
  • Basic understanding of Node.js and WebSocket protocol.
  • Basic understanding of Raspberry Pi GPIO pins.

Dependencies

We will need the following dependencies for this project:

  • ws (WebSocket library for Node.js)
  • rpi-ws281x-native (Library for controlling WS281x LEDs)

To install these libraries, run:

npm install ws rpi-ws281x-native

Wiring up the LED

Connect the ground pin of the LED to one of the GND pins on the Raspberry Pi.

Connect the Vcc pin of the LED to the 5V pin on the Raspberry Pi.

Connect the Data Input pin of the LED to GPIO 18 (physical pin 12) on the Raspberry Pi.

Code

Here is the complete code for controlling the RGB LED using WebSocket:

const WebSocket = require('ws');
const ws281x = require('rpi-ws281x-native');

// Configure LED strip
const NUM_LEDS = 1;
const pixelData = new Uint32Array(NUM_LEDS);
ws281x.init(NUM_LEDS);

// Initialize WebSocket server
const wss = new WebSocket.Server({port: 8080});

wss.on('connection', (ws) => {
    console.log('WebSocket connection established.');

    // Set default LED color
    setPixelColor('#000000');

    ws.on('message', (msg) => {
        let data;
        try {
            data = JSON.parse(msg);
        } catch (e) {
            console.log('Invalid JSON received:', msg);
            return;
        }

        if (data.color) {
            console.log('Received color:', data.color);
            setPixelColor(data.color);
        } else {
            console.log('Invalid message:', data);
        }
    });
});

function setPixelColor(color) {
    const rgb = hexToRgb(color);
    pixelData[0] = (rgb.r << 16) | (rgb.g << 8) | rgb.b;
    ws281x.render(pixelData);
}

// Utility functions
function hexToRgb(hex) {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

Explanation

In the above code, we first configure the LED strip with the number of LEDs and initialize the WebSocket server.

When a WebSocket connection is established, we set the default LED color to black and listen for incoming messages. When we receive a message, we parse it as JSON. If the message contains a color property, we update the LED color to the received color.

The setPixelColor() function converts the received color from hex format to RGB format and sets the color of the LED.

Usage

To run the application, save the code in a file (e.g. server.js) on your Raspberry Pi and run:

sudo node server.js

By default, the WebSocket server listens on port 8080. You can then access the server by opening your browser and navigating to the IP address of your Raspberry Pi followed by :8080.

Output

When you access the server using your browser, you should see a simple page with a color picker. Choosing a color on the color picker should change the color of the LED connected to GPIO 18 on your Raspberry Pi.

Important Points

  • Make sure to correctly wire up the LED before running the application.
  • Remember to start the application with sudo privileges in order to access GPIO pins.
  • WebSocket connections are not encrypted by default, be careful sending sensitive data.

Summary

In this tutorial, we built a simple Node.js application running on a Raspberry Pi that allows us to control an RGB LED using WebSocket protocol. We learned how to configure and control WS281x LEDs with Node.js and how to use the WebSocket module to communicate with a web interface. With this knowledge, you can create all sorts of fun projects using your Raspberry Pi and some RGB LEDs!

Published on: