.. note::

    Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

    **Why Join?**

    - **Expert Support**: Solve post-sale issues and technical challenges with help from our community and team.
    - **Learn & Share**: Exchange tips and tutorials to enhance your skills.
    - **Exclusive Previews**: Get early access to new product announcements and sneak peeks.
    - **Special Discounts**: Enjoy exclusive discounts on our newest products.
    - **Festive Promotions and Giveaways**: Take part in giveaways and holiday promotions.

    👉 Ready to explore and create with us? Click [|link_sf_facebook|] and join today!

.. _1.1.2_py:

1.1.2 RGB LED
====================

Introduction
--------------

In this project, we will control an RGB LED to flash various colors.

Required Components
------------------------------

In this project, we need the following components. 

.. image:: ../img/list_rgb_led.png
    :align: center

It's definitely convenient to buy a whole kit, here's the link: 

.. list-table::
    :widths: 20 20 20
    :header-rows: 1

    *   - Name	
        - ITEMS IN THIS KIT
        - LINK
    *   - Raphael Kit
        - 337
        - |link_Raphael_kit|

You can also buy them separately from the links below.

.. list-table::
    :widths: 30 20
    :header-rows: 1

    *   - COMPONENT INTRODUCTION
        - PURCHASE LINK

    *   - :ref:`cpn_gpio_extension_board`
        - |link_gpio_board_buy|
    *   - :ref:`cpn_breadboard`
        - |link_breadboard_buy|
    *   - :ref:`cpn_wires`
        - |link_wires_buy|
    *   - :ref:`cpn_resistor`
        - |link_resistor_buy|
    *   - :ref:`cpn_rgb_led`
        - |link_rgb_led_buy|


Schematic Diagram
-----------------------

After connecting the pins of R, G, and B to a current limiting resistor,
connect them to the GPIO17, GPIO18, and GPIO27 respectively. The longest
pin (GND) of the LED connects to the GND of the Raspberry Pi. When the
three pins are given different PWM values, the RGB LED will display
different colors.

============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO17       Pin 11   0        17
GPIO18       Pin 12   1        18
GPIO27       Pin 13   2        27
============ ======== ======== ===

.. image:: ../img/rgb_led_schematic.png

Experimental Procedures
----------------------------

**Step 1:** Build the circuit.

.. image:: ../img/image61.png

**Step 2:** Open the code file.

.. raw:: html

   <run></run>

.. code-block::

    cd ~/raphael-kit/python

**Step 3:** Run.

.. raw:: html

   <run></run>

.. code-block::

    sudo python3 1.1.2_rgbLed.py

After the code runs, you will see that RGB displays red, green, blue,
yellow, pink, and cyan.

**Code**

.. note::

    You can **Modify/Reset/Copy/Run/Stop** the code below. But before that, you need to go to  source code path like ``raphael-kit/python``. After modifying the code, you can run it directly to see the effect.

.. raw:: html

    <run></run>

.. code-block:: python

    import RPi.GPIO as GPIO
    import time
    # Set up a color table in Hexadecimal
    COLOR = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF]
    # Set pins' channels with dictionary
    pins = {'Red':17, 'Green':18, 'Blue':27}

    def setup():
        global p_R, p_G, p_B
        GPIO.setmode(GPIO.BCM)
        # Set all LedPin's mode to output and initial level to High(3.3v)
        for i in pins:
            GPIO.setup(pins[i], GPIO.OUT, initial=GPIO.HIGH)

        p_R = GPIO.PWM(pins['Red'], 2000)
        p_G = GPIO.PWM(pins['Green'], 2000)
        p_B = GPIO.PWM(pins['Blue'], 2000)
        p_R.start(0)
        p_G.start(0)
        p_B.start(0)

    # Define a MAP function for mapping values.  Like from 0~255 to 0~100
    def MAP(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

    # Define a function to set up colors
    def setColor(color):
    # configures the three LEDs' luminance with the inputted color value.
        R_val = (color & 0xFF0000) >> 16
        G_val = (color & 0x00FF00) >> 8
        B_val = (color & 0x0000FF) >> 0

        # Map color value from 0~255 to 0~100
        R_val = MAP(R_val, 0, 255, 0, 100)
        G_val = MAP(G_val, 0, 255, 0, 100)
        B_val = MAP(B_val, 0, 255, 0, 100)
        
        # Change the colors
        p_R.ChangeDutyCycle(R_val)
        p_G.ChangeDutyCycle(G_val)
        p_B.ChangeDutyCycle(B_val)

        print ("color_msg: R_val = %s,  G_val = %s, B_val = %s"%(R_val, G_val, B_val))  

    def main():
        while True:
            for color in COLOR:
                setColor(color)# change the color of the RGB LED
                time.sleep(0.5)

    def destroy():
        # Stop all pwm channel
        p_R.stop()
        p_G.stop()
        p_B.stop()
        # Release resource
        GPIO.cleanup()

    if __name__ == '__main__':
        setup()
        try:
            main()
        except KeyboardInterrupt:
            destroy()

**Code Explanation**

.. code-block:: python

    p_R = GPIO.PWM(pins['Red'], 2000)
    p_G = GPIO.PWM(pins['Green'], 2000)
    p_B = GPIO.PWM(pins['Blue'], 2000)

    p_R.start(0)
    p_G.start(0)
    p_B.start(0)

Call the ``GPIO.PWM()`` function to define Red, Green and Blue as PWM pins
and set the frequency of PWM pins to 2000Hz, then Use the ``Start()``
function to set the initial duty cycle to zero.

.. code-block:: python

    def MAP(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

Define a MAP function for mapping values. For instance, x=50, in_min=0,
in_max=255, out_min=0, out_max=100. After the map function mapping, it
returns ``(50-0) \* (100-0)/(255-0) +0=19.6``, meaning that 50 in 0-255
equals 19.6 in 0-100.

.. code-block:: python

    def setColor(color):
        R_val = (color & 0xFF0000) >> 16
        G_val = (color & 0x00FF00) >> 8
        B_val = (color & 0x0000FF) >> 0

Configures the three LEDs’ luminance with the inputted color value,
assign the first two values of the hexadecimal to R_val, the middle two
assigned to G_val, the last two values to B_val. For instance, if
color=0xFF00FF, R_val=（0xFF00FF & 0xFF0000）>> 16 = 0xFF, G_val = 0x00,
B_val=0xFF.

.. code-block:: python

    R_val = MAP(R_val, 0, 255, 0, 100)
    G_val = MAP(G_val, 0, 255, 0, 100)
    B_val = MAP(B_val, 0, 255, 0, 100)

Use map function to map the R,G,B value among 0~255 into PWM duty cycle
range 0-100.

.. code-block:: python

    p_R.ChangeDutyCycle(R_val) 
    p_G.ChangeDutyCycle(G_val)
    p_B.ChangeDutyCycle(B_val)

Assign the mapped duty cycle value to the corresponding PWM channel to
change the luminance.

.. code-block:: python

    for color in COLOR:
        setColor(color)
        time.sleep(0.5)

Assign every item in the COLOR list to the color respectively and change
the color of the RGB LED via the ``setColor()`` function.

Phenomenon Picture
------------------------

.. image:: ../img/image62.jpeg
