How it works...

To start with, we define the hardware setup by defining the states required to Enable and Disable the LED depending on the type of RGB LED (common cathode) used. If you are using a common anode device, just reverse the Enable and Disable states.

Next, we define the GPIO mapping to the pins to match the wiring we did previously.

We also define some basic color combinations by combining red, green, and/or blue together, as shown in the following diagram:

LED color combinations

We define a series of useful functions, the first being led_setup(), which will set the GPIO numbering to GPIO.BOARD and define all the pins that are to be used as outputs. We also call a function named led_clear(), which will set the pins to the default state with all the pins disabled.

This means that the LED pins, 1-5 (the common cathode on each LED), are set to HIGH, while the RGB pins (the separate anodes for each color) are set to LOW.

We create a function called led_gpiocontrol() that will allow us to set the state of one or more pins. The isinstance() function allows us to test a value to see whether it matches a particular type (in this case, a single integer); then we can either set the state of that single pin or iterate through the list of pins and set each one.

Next, we define two functions, led_activate() and led_deactivate(), which will enable and disable the specified LED and color. Finally, we define led_time(), which will allow us to specify an LED, color, and time to switch it on for.

We also create led_cleanup() to reset the pins (and LEDs) to the default values and call GPIO.cleanup() to release the GPIO pins in use.

This script is intended to become a library file, so we will use the if __name__=='__main__' check to only run our test code when running the file directly:

By checking the value of __name__, we can determine whether the file was run directly (it will equal __main__) or whether it was imported by another Python script.

This allows us to define a special test code that is only executed when we directly load and run the file. If we include this file as a module in another script, then this code will not be executed.

As before, we will use try/finally to allow us to always perform cleanup actions, even if we exit early.

To test the script, we will set the LEDs to light up in various colors, one after another.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.105.215