# Blink

The LED Blink application is a project that allows the user to control the blinking of an LED using an [SMD ](https://docs.acrome.net/electronics/smd-red)and an [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module). This project is designed for simplicity, making it an ideal starting point for those wishing to experience the SMD hardware control using [the SMD libraries](https://docs.acrome.net/software/libraries).

<div data-full-width="false"><figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FZgc7g1LvHo35yPHkFEe8%2FBlink.gif?alt=media&#x26;token=efa327ba-e73a-4eee-b4b5-347bf3abf60e" alt=""><figcaption><p>"Blink" Project</p></figcaption></figure></div>

**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))

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

**Project Key Components**

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

  The SMD acts as a bridge between the script and the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module). It is responsible for interpreting the commands sent by the script and translating them into actions that toggle the RGB module.
* [**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.
* [**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 turn the RGB LED on or off, adjust the color, or set a specific blinking pattern.

**Project Key Features**

* **Detailed Control over the LED**

  The user can easily control the LED of the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) colors by simply using the necessary function of SMD libraries. The LED on the module can emit all RGB color values.

## **Step 2: Assemble**

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) 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%2FcW3QgYD7c9zn6oyYEw3b%2Fblink11.png?alt=media&#x26;token=be78ed2a-07b1-453e-9f3a-40d564b0079c" 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 [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).
2. **Experience and Customize:**
   * Explore different blinking patterns, change the color of the RGB LED to suit your preferences.

## Codes

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

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

def USB_Port():
    """
    Detects the USB serial port based on the operating system.
    Returns the detected port or None if no suitable port is found.
    """
    ports = list(comports())
    usb_names = {
        "Windows": ["USB Serial Port"],  # Serial port names specific to Windows
        "Linux": ["/dev/ttyUSB"],        # Serial port names specific to Linux
        "Darwin": [                      # Serial port names specific to macOS
            "/dev/tty.usbserial",
            "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART",
            "/dev/tty.wchusbserial",
            "/dev/cu.usbserial",
        ]
    }
    
    # Get the operating system name
    os_name = system()
    if ports:
        for port, desc, hwid in sorted(ports):
            # Check if any known USB name matches the port or its description
            if any(name in port or name in desc for name in usb_names.get(os_name, [])):
                print("Connected to:", port)
                return port
        # If no suitable port is found, display all available ports
        print("Available ports:")
        for port, desc, hwid in ports:
            print(f"Port: {port}, Description: {desc}, HWID: {hwid}")
    else:
        print("No ports detected!")
    return None

# Detect the serial port dynamically
SerialPort = USB_Port()
if not SerialPort:
    print("No suitable USB port found! Exiting...")
    exit(1)

# Define constants
baudrate = 115200       # Baud rate for communication
ID = 0                  # ID of the SMD
rgb_module_id = 5       # ID of the RGB LED module

try:
    # Initialize the Master module for communication with the SMD
    master = Master(SerialPort, baudrate)       # Sets up the USB gateway module
    master.attach(Red(ID))                      # Connects to the SMD with the specified ID
    master.scan_modules(ID)                     # Scans and identifies connected modules to the SMD

    # RGB LED control loop
    while True:
        # Set the RGB LED to red
        master.set_rgb(ID, rgb_module_id, 255, 0, 0)        # RGB values: 255 (Red), 0 (Green), 0 (Blue)
        time.sleep(0.5)                                     # Delay to control blinking frequency
        # Turn off the RGB LED
        master.set_rgb(ID, rgb_module_id, 0, 0, 0)          # RGB values: 0 (All colors off)
        time.sleep(0.5)                                     # Delay to control blinking frequency

except FileNotFoundError as e:
    # Handle the case when the serial port is not found
    print(f"Error: {e}")
    print("Make sure the specified serial port exists and is connected.")
except Exception as e:
    # Handle any unexpected errors
    print(f"Unexpected error: {e}")                                    # Value can be changed to see how the blinking frequency changes
```

{% endcode %}
{% endtab %}

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

```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
void setup() {
    master.begin();                 // Starts the communication
    master.scanModules();           // Scans for the connected modules
}

void loop() {
    master.setRGB(rgb_module_id, 255, 0, 0);    // Numbers are correspond to the R - G - B color values
    delay(500);                                 // Value can be changed to see how the blinking frequency changes
    master.setRGB(rgb_module_id, 0, 0, 0);      // Sets all colors to zero, meaning turning the RGB LED off
    delay(500);                                 // Value can be changed to see how the blinking frequency changes
}

```

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