RGB LED - Writing the code#
Write out the code seen below:
import board
import time
import pwmio
import random
blueLED = pwmio.PWMOut(board.GP0)
greenLED = pwmio.PWMOut(board.GP1)
redLED = pwmio.PWMOut(board.GP2)
while True:
redLED.duty_cycle = random.randint(0, 65534)
blueLED.duty_cycle = random.randint(0, 65534)
greenLED.duty_cycle = random.randint(0, 65534)
time.sleep(2)
If all is running properly, the LED should light up with a different random colour every 2 seconds.
Coding PWM#
For the first time, we have not used the digitalio
module but instead pwmio. This is a module that allows us to pulse width modulate output from our LEDs (see previous page for a description of PWM).
To create objects for our output pins, we instead only need one function pwmio.PWMOut()
which assigns the pin and specifies the direction as Out in one step.
To change the duty cycle of the output and achieve PWM, we simply assign an integer between 0 and 65535 to output.duty_cycle
. Zero corresponds to a 0% duty cycle while 65535 (or \(2^{16}-1\)) is a 100% duty cycle.
Using random numbers#
Random numbers can be incredibly useful in programming and there are a variety of ways generate them.
Here we have used the function randint()
from the random
module. This takes two integers as inputs and returns a randomly chosen integer between those two integers inclusive. In our code, this allows us to generate a random value for the duty cycles of the red, green and blue light sources. This changes the respective brightnesses, which combine to create a random colour every two seconds.
Beyond this example, random numbers may be useful for random data sampling.
Totally Random
There are a number of useful functions within the random
module that allow a variety of different methods for random number generation.
randrange()
= Similar torandint
but allows you to specify a range with steps. For example,randrange(1, 9, 2)
will only choose from even numbers between 1 and 10.choice()
= Randomly selects an element from an inputted list.uniform()
= Similar torandint
but generates decimal numbers (floats) within a given range.
For official documentation, see here.