RasPi RGB LED WebSocket

What Is an RGB LED?

An RGB LED is a type of LED that can produce various colors by combining red, green, and blue light. Each of the three colors can be adjusted from 0 to 255 (using PWM), creating millions of color combinations.

  • Red, Green, Blue Pins: Each pin controls one of the RGB colors.
  • PWM (Pulse Width Modulation): Controls the brightness of each color by adjusting the duty cycle.

Prerequisites

Before starting the project, ensure you have the following components:

  1. Raspberry Pi: Any model (e.g., Raspberry Pi 4, Zero).
  2. RGB LED: A common cathode RGB LED.
  3. Resistors: Three 220-ohm resistors to limit current to the RGB LED.
  4. Breadboard and Jumper Wires: For easy assembly.
  5. Web Browser: For testing the WebSocket client.
  6. Python Installed: Pre-installed on Raspberry Pi OS.

Step 1: Assemble the Circuit

Components and Connections:

  1. RGB LED:
    • Connect the common cathode (longest pin) to GND (Pin 6).
    • Connect the red pin (usually the longest of the three) to GPIO17 (Pin 11).
    • Connect the green pin to GPIO27 (Pin 13).
    • Connect the blue pin to GPIO22 (Pin 15).
  2. Resistors:
    • Place a 220-ohm resistor between each RGB pin and the GPIO pins to prevent excessive current.

Circuit Diagram:

Raspberry Pi PinRGB LED PinDescription
GPIO17 (Pin 11)RedControls red color
GPIO27 (Pin 13)GreenControls green color
GPIO22 (Pin 15)BlueControls blue color
GND (Pin 6)Common CathodeCommon ground for LED

Step 2: Install Required Libraries

To control the RGB LED and set up WebSocket communication, you need the RPi.GPIO and websockets libraries. Install them with the following commands:

pip install RPi.GPIO websockets

Step 3: Write the WebSocket Server Code

Now let’s create a WebSocket server that listens for color data from the client and sets the RGB LED accordingly.

Python WebSocket Server Code:

import asyncio
import websockets
import RPi.GPIO as GPIO

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT) # Red pin
GPIO.setup(27, GPIO.OUT) # Green pin
GPIO.setup(22, GPIO.OUT) # Blue pin

# PWM setup for RGB LED control
red = GPIO.PWM(17, 100)
green = GPIO.PWM(27, 100)
blue = GPIO.PWM(22, 100)

red.start(0)
green.start(0)
blue.start(0)

async def set_color(websocket, path):
while True:
color_data = await websocket.recv() # Receive color data
print(f"Received color data: {color_data}")

# Parse RGB values from the received message
try:
r, g, b = map(int, color_data.split(','))
red.ChangeDutyCycle(r) # Set red intensity
green.ChangeDutyCycle(g) # Set green intensity
blue.ChangeDutyCycle(b) # Set blue intensity
await websocket.send(f"Color set to {r}, {g}, {b}")
except ValueError:
await websocket.send("Invalid color data. Please send values in the format 'r,g,b'.")

# Start the WebSocket server
async def main():
server = await websockets.serve(set_color, "localhost", 8765)
print("WebSocket server running on ws://localhost:8765")
await server.wait_closed()

# Run the event loop
asyncio.run(main())

Explanation of the WebSocket Server Code:

  1. GPIO Setup:
    • GPIO.setmode(GPIO.BCM): Sets the Raspberry Pi pin numbering to BCM.
    • GPIO.setup(): Configures GPIO pins 17, 27, and 22 as output pins connected to the RGB LED.
    • GPIO.PWM(): Creates a PWM instance for each RGB pin to control brightness levels.
  2. WebSocket Server:
    • websockets.serve(): Starts a WebSocket server that listens on localhost:8765.
    • set_color(): Handles incoming WebSocket connections. It receives the RGB values from the client and sets the LED colors accordingly.
  3. Color Control:
    • The color data is expected in the format “r,g,b”, where r, g, and b are the intensities of red, green and blue (values from 0 to 100 for PWM).

Step 4: Create the WebSocket Client

Now let’s build a simple HTML and JavaScript client to send color data to the Raspberry Pi and control the RGB LED.

HTML and JavaScript WebSocket Client:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RGB LED WebSocket Client</title>
</head>
<body>
<h1>RGB LED Control</h1>
<label for="red">Red: </label><input type="range" id="red" min="0" max="100"><br>
<label for="green">Green: </label><input type="range" id="green" min="0" max="100"><br>
<label for="blue">Blue: </label><input type="range" id="blue" min="0" max="100"><br>
<button id="sendColor">Set Color</button>

<script>
let socket = new WebSocket("ws://localhost:8765");

socket.onopen = function() {
console.log("Connected to WebSocket server.");
};

document.getElementById("sendColor").onclick = function() {
let r = document.getElementById("red").value;
let g = document.getElementById("green").value;
let b = document.getElementById("blue").value;

let colorData = `${r},${g},${b}`;
socket.send(colorData); // Send color data to the server

console.log(`Sent color: ${colorData}`);
};

socket.onmessage = function(event) {
alert(event.data); // Show response from server
};
</script>
</body>
</html>

Explanation of the WebSocket Client Code:

  1. WebSocket Connection:
    • new WebSocket(“ws://localhost:8765”): Connects to the WebSocket server running on Raspberry Pi.
    • socket.onopen: Fires when the WebSocket connection is established.
  2. Control RGB LED:
    • The client allows users to control the RGB values using sliders (ranging from 0 to 100).
    • The Send Color button sends the selected RGB values to the Raspberry Pi server in the format “r,g,b”.
  3. Server Response:
    • When the Raspberry Pi server successfully receives the color data, it sends a confirmation message back to the client.

Step 5: Test the System

Start the WebSocket Server:
Run the Python server script on your Raspberry Pi:

python3 rgb_led_websocket_server.py

Open the WebSocket Client:
Open the index.html file in a web browser.

Control the LED:

  • Use the sliders to adjust the RGB values.
  • Click the Set Color button to change the color of the LED.

Troubleshooting

  1. LED Not Changing Color:
    • Ensure the circuit is correctly wired, and the resistors are placed between the GPIO pins and the LED.
    • Double-check the GPIO pin numbers in the Python code.
  2. WebSocket Connection Error:
    • Ensure the server is running and the correct WebSocket address (ws://localhost:8765) is used in the client.

Leave a Comment

BoxofLearn