# Action - Reaction

The LED toggle application with a button is the most used project for simple input/output project example. This project allows the user to control the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) with the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) by simply toggling an LED.

<figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FJxI4ss7nMSSmb6DQeT6G%2Faction_reaction.gif?alt=media&#x26;token=2f003e5c-f95e-47f0-84a4-db7dd9e23ce7" alt=""><figcaption></figcaption></figure>

**About Tools and Materials:**

[SMD Red](https://docs.acrome.net/electronics/smd-red) ([Purchase Here](https://www.robotshop.com/products/acrome-smd-red-smart-brushed-motor-driver-with-speed-position-and-current-control-modes))

[SMD USB Gateway](https://docs.acrome.net/electronics/gateway-modules/usb-gateway-module) ([Purchase Here](https://www.robotshop.com/products/acrome-usb-gateway-module-acrome-smd-products))

[Arduino Gateway Module](https://docs.acrome.net/electronics/gateway-modules/arduino-gateway-module) ([Purchase Here](https://www.robotshop.com/products/acrome-arduino-gateway-shield-module-acrome-smd-products))

[RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) ([Purchase Here](https://www.robotshop.com/products/acrome-rgb-led-add-on-module-acrome-smd-products))

[Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) ([Purchase Here](https://www.robotshop.com/products/acrome-button-add-on-module-acrome-smd-products?pr_prod_strat=e5_desc\&pr_rec_id=e23ece12f\&pr_rec_pid=8120246796449\&pr_ref_pid=8121226592417\&pr_seq=uniform))

## **Step 1: Hardware & Software Overview**

**Project Key Components**

1. [**SMD**](https://docs.acrome.net/electronics/smd-red)

   The SMD acts as a bridge between the script and the modules. It is responsible for interpreting the commands sent by the script and translating them into actions that read input from the button module and toggle the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).
2. [**RGB LED Module**](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module)

   The [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) is designed to emit different colors, allowing users to experiment with different lighting effects.
3. [**Button Module**](https://docs.acrome.net/electronics/add-on-modules/button-module)

   The [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) is the physical interface for receiving input from the user. The input can be used to trigger the script in an encoded way.
4. [**SMD Libraries**](https://docs.acrome.net/software/libraries)

   The SMD library is at the heart of the application. It communicates with the SMD using a specific communication protocol, sending commands to read the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) and toggle the LED on the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).

**Project Key Features**

* **A Basic Physical Interaction**

  The application supports a toggle functionality, allowing the user to press the button to toggle the LED. This provides a simple physical interaction with project.
* **Visualizing the Input**

  The [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) serves as a visual indicator of the current state of the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module). When the button is pressed, the LED turns on; when the button is not pressed, the LED turns off.

## **Step 2: Assemble**

**Getting Started**

1. **Hardware Setup**
   * Connect the SMD to the PC or Arduino board using [USB Gateway Module](https://docs.acrome.net/electronics/gateway-modules/usb-gateway-module) or [Arduino Gateway Module](https://docs.acrome.net/electronics/gateway-modules/arduino-gateway-module).
   * Connect the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) and the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) to the SMD using an RJ-45 cable.
   * Make sure that the SMD is powered and all connections are correct

#### Project Wiring Diagram

<figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FJDtBqkq2E5XfAHktrBzy%2FAction1.png?alt=media&#x26;token=699c8f34-896f-493e-b19e-a5f1eacfb6d7" alt=""><figcaption></figcaption></figure>

## Step 3: Run & Test

1. **Run the Script**
   * Run the script on your computer. This will establish communication with the SMD and initiate control of the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) and [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).
2. **Toggle LED State**
   * Press the button on the [Button Module](https://docs.acrome.net/electronics/add-on-modules/button-module) to toggle the RGB LED. Observe the visual feedback of the LED.

## Codes

{% tabs %}
{% tab title="Python Code" %}
{% code lineNumbers="true" %}

```python
from serial.tools.list_ports import comports
from platform import system
from smd.red import *

baudrate = 115200       # Baud rate of communication
ID = 0                  # ID of the SMD
rgb_module_id = 5       # ID of the RGB LED module
button_module_id = 5    # ID of the button module


def USB_Port():
    """
    Scans and identifies a compatible USB port for the current operating system.

    Returns:
        str: The detected USB port or None if no suitable port is found.
    """
    # Get a list of available ports
    ports = list(comports())
    
    # Known USB port names for different operating systems
    usb_names = {
        "Windows": ["USB Serial Port"],  # Names specific to Windows
        "Linux": ["/dev/ttyUSB"],        # Names specific to Linux
        "Darwin": [                      # Names specific to macOS
            "/dev/tty.usbserial",
            "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART",
            "/dev/tty.wchusbserial",
            "/dev/cu.usbserial",
        ]
    }

    # Detect the operating system
    os_name = system()
    print(f"Operating System: {os_name}")

    if ports:
        for port, desc, hwid in sorted(ports):
            # Check if the port matches any known USB names
            if any(name in port or name in desc for name in usb_names.get(os_name, [])):
                print(f"USB device detected on port: {port}")
                return port  # Return the first matching port
        # If no suitable port is found, print the list of available ports
        print("No suitable USB device found. Available ports:")
        for port, desc, hwid in ports:
            print(f"Port: {port}, Description: {desc}, HWID: {hwid}")
    else:
        print("No ports detected!")
    return None


try:
    # Find a valid serial port
    SerialPort = USB_Port()
    if not SerialPort:
        raise Exception("No compatible USB port found. Please check your connection.")

    print(f"Using serial port: {SerialPort}")

    # Initialize the SMD module
    master = Master(SerialPort, baudrate)       # Defines the USB gateway module
    master.attach(Red(ID))                      # Gives access to the SMD of specified ID
    master.scan_modules(ID)                     # Scans and identifies the modules connected to the SMD

    # Main loop
    while True:
        # Get the button state from the SMD
        button_state = master.get_button(ID, button_module_id)

        if button_state == 1:
            # Set the RGB LED to red
            master.set_rgb(ID, rgb_module_id, 255, 0, 0)  # RGB values for red
        else:
            # Turn off the RGB LED
            master.set_rgb(ID, rgb_module_id, 0, 0, 0)    # RGB values for off

except Exception as e:
    print(f"Error: {e}")
```

{% endcode %}
{% endtab %}

{% tab title="Arduino Code" %}
{% code lineNumbers="true" %}

```cpp
#include <Acrome-SMD.h>

#define ID        0           // ID of the SMD
#define BAUDRATE  115200      // Baud rate of the communication

Red master(ID, Serial, BAUDRATE);    // Defines the Arduino gateway module

int rgb_module_id = 1;              // ID of the RGB LED module
int button_module_id = 1;           // ID of the button module

int button_state = 0;               // Variable to store the button state

void setup() {
    master.begin();                 // Starts the communication
    master.scanModules();           // Scans for the connected modules
}

void loop() {
    button_state = master.getButton(button_module_id);      // Getting the button state and storing it
    
    if (button_state == 1) {
        master.setRGB(rgb_module_id, 255, 0, 0);    // Numbers are correspond to the R - G - B color values
    }

    else {
        master.setRGB(rgb_module_id, 0, 0, 0);      // Sets all colors to zero, meaning turning the RGB LED off
    }
}

```

{% endcode %}
{% endtab %}
{% endtabs %}
