SunFounder 37 Modules Sensor Kit V2.0 for Raspberry PI 2: Web controlled RGB – LED

20151115_rgb_led The second module in the SunFounder 37 Modules Sensor kit is a RGB – LED. Using PWM it is possible to combine the 3 colors (red, green and blue) to almost any other color. Again I will use a web frontend to control this LED

As in the dual color LED example „Python bottle“ will be used again as a server framework. This time we build a simple HTML5 page with 3 number inputs to change the color of each channel.

First let’s see the server-code:

./server.py

#!/usr/bin/env python
from bottle import route, run, template
import RPi.GPIO as GPIO
import time

leds = {"red":11, "green": 12, "blue": 13}
colors = {}

# Setup GPIO to PWM
def setup():
        GPIO.setmode(GPIO.BOARD)
        for led in leds:
                GPIO.setup(leds[led],GPIO.OUT)
                colors[led] = GPIO.PWM(leds[led],1000.)
                colors[led].start(0)

# Cleanup on exit
def destroy():
        GPIO.cleanup()

# change the duty-cycle of each channel to given value
def updateLeds(r,g,b):
    print "Changing color to ",r,g,b
    print
    colors["red"].ChangeDutyCycle(r)
    colors["green"].ChangeDutyCycle(g)
    colors["blue"].ChangeDutyCycle(b)

# load the user interface
@route('/')
def index():
        return template('index')

# api to control the 3 channels
@route('/<r>,<g>,<b>')
def led(r,g,b):
        updateLeds(int(r),int(g),int(b))

# let's run the server
if __name__ == '__main__':
        setup()
        try:
                run(host="0.0.0.0", port=8080)
        finally:
                destroy()

For the html-template we use HTML5 to get a simple number-input field:

./views/index.tpl

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
function updateColors() {
  var r = $('#red').val();
  var g = $('#green').val();
  var b = $('#blue').val();
  var url = "/" + r + "," + g + "," + b;
  $.get(url, function(){})
}
</script>

<input type="number" name="red" min="0" max="100" id="red" step="10" value="0" oninput="updateColors()"/> red<br/>
<input type="number" name="green" min="0" max="100" id="green" step="10" value="0" oninput="updateColors()"/> green<br/>
<input type="number" name="blue" min="0" max="100" id="blue" step="10" value="0" oninput="updateColors()"/> blue<br/>
</html>

That’s all. Just start the server now with
python server.py
and open the user-interface in your browser:
http://ip.of.your.raspberry:8080
Whenever a value is changed on the website the LED will be updated immediatly

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.