In this tutorial we'll learn how to change color of an RGB LED with a button
Materiales:
- Raspberry Pi with Raspbian or similar
- RGB LED
- Button
- 4x 1K resistors
- 5 wires male/female and 2 wires male/male
- Breadboard
The code to change the RGB LED color with a button is:
import RPi.GPIO as GPIO
def next_rgb_color(r_pin, g_pin, b_pin, data):
led_colors = [(1, 0, 0), (1, 0, 1), (0, 0, 1),
(0, 1, 1), (0, 1, 0), (1, 1, 0)]
GPIO.output([r_pin, g_pin, b_pin], led_colors[data['index']])
data['index'] += 1 # Increment index
if data['index'] >= len(led_colors): # If index out of range
data['index'] = 0 # Restart from first color
R_PIN = 11
G_PIN = 13
B_PIN = 15
BUTTON_PIN = 12 # Set the BUTTON pin number into a variable
data = {'index': 0} # Create a dict because it's mutable
GPIO.setmode(GPIO.BOARD) # Set GPIO mode to BOARD to use pin numbers
GPIO.setup(R_PIN, GPIO.OUT, initial=0) # Prepare Red pin
GPIO.setup(G_PIN, GPIO.OUT, initial=0) # Prepare Green pin
GPIO.setup(B_PIN, GPIO.OUT, initial=0) # Prepare Blue pin
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Prepare BUTTON pin
# Use def function to pass parameters
btn_function = lambda x: next_rgb_color(R_PIN, G_PIN, B_PIN, data)
# Setup event on rising edge
GPIO.add_event_detect(BUTTON_PIN, GPIO.RISING,
callback=btn_function,
bouncetime=300)
raw_input("Exit script by pressing enter")
GPIO.cleanup() # Clear GPIO
Here you can see the circuit of the RGB LED, button and rPi
Here you can see a video about how to assemble the circuit and run the code:
Remember! I use the GPIO mode BOARD, that means I always refer to the GPIO pins using their PIN number. If you uses GPIO in mode BCM you will need to translate the PIN numbers to GPIO number, you can use this GPIO pinout scheme to do that: Raspberry PI: GPIO pinout