# Autonomous Lighting

The autonomous lighting project is a basic environmental interaction example. It imitates a night lamp, using the [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) to sense the light level and let the user decide what level is dark enough to turn on the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module). It also helps with energy efficiency by turning the LED when it is bright enough.

<figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FesT8GAdmSKiZfkMWTTKH%2Fautonomous_light.gif?alt=media&#x26;token=678c218f-51fb-4428-9dca-a90acd36b7b0" 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))

[Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module)  ([Purchase Here](https://www.robotshop.com/products/acrome-ambient-light-sensor-add-on-module-acrome-smd-products))

## **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 [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-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. [**Ambient Light Sensor Module**](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module)

   The [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) is measures the surrounding light intensity and provides feedback of the intensity to the script, allowing the user to decide whether to turn on or off the LED.
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 [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) and toggle the LED on the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).

**Project Key Features**

* **Automatic Light Sensing**

  The [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) is a input module and the bridge between the physical world and the script, allowing the user to read the data of the environment.
* **Energy-Efficient Operation**

  The [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) allows the user to only turn on the light when it is dark and needed, thus, it helps with the energy efficiency.
* **Real-time Monitoring**

  The script can also be modified to monitor the ambient light intensity in real-time.

## **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 [Ambient Light Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) and 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%2FUbHxgs51Nf4fymUn4Sia%2FAutonomous%20Lighting1.png?alt=media&#x26;token=a2e6b11d-c58f-4654-ae6e-b0e91312ef91" 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, the [Ambient Light Module](https://docs.acrome.net/electronics/add-on-modules/ambient-light-sensor-module) and the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module).
2. **Observe Autonomous Operation**
   * Observe how the LED automatically turns on when the environment becomes dark and turns off when there is sufficient ambient light.

## 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
ambient_module_id = 5   # ID of the ambient light sensor 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 in ports:
            # Check if the port matches any known USB names
            if any(name in port.device or name in port.description for name in usb_names.get(os_name, [])):
                print(f"USB device detected on port: {port.device}")
                return port.device  # 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 in ports:
            print(f"Port: {port.device}, Description: {port.description}, HWID: {port.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 ambient light data from the sensor
        light = master.get_light(ID, ambient_module_id)  # Variable to store the ambient light data
        print(f"Ambient light level: {light}")           # Print the value to observe

        if light < 30:
            # Set the RGB LED to white
            master.set_rgb(ID, rgb_module_id, 255, 255, 255)  # RGB values for white
        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 ambient_module_id = 1;          // ID of the ambient module

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

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

void loop() {
    light = master.getLight(ambient_module_id);      // Getting the ambient light value and storing it
    
    if (light < 30) {
        master.setRGB(rgb_module_id, 255, 255, 255);    // 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 %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.acrome.net/smd-applications/basics/autonomous-lighting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
