# Security System

The Security System project is a simple yet useful real-life scenario application. It uses a [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module), the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) and the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) to work like a geniune security system. The system is designed to be activated when there is a movement in designated area.

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

[Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) ([Purchase Here](https://www.robotshop.com/products/acrome-ultrasonic-distance-sensor-add-on-module-acrome-smd-products))

[Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) ([Purchase Here](https://www.robotshop.com/products/acrome-buzzer-sound-add-on-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**

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 [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) and actuate the visual and audible warning signals.
2. [**Ultrasonic Distance Sensor Module**](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module)

   The [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) measures the distance between the sensor and an object in its path. It provides distance data to the script for security monitoring.
3. [**Buzzer Module**](https://docs.acrome.net/electronics/add-on-modules/buzzer-module)

   The [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) serves as the audible warning. It emits sound when activated when there is an object in the designated area.
4. [**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 used to provide visual warning. It can emit different colors and light intensities as programmed.
5. [**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 [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) and actuate the visual and audible warnings, the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) and the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module).

**Project Key Features**

* **Distance-based Security Monitoring**

  The Security System continuously monitors the distance measured by the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module). If the distance of the detected object is equal or closer than the determined distance value, the alert system will be activated.
* **Visual Feedback with the** [**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) displays red and blue lights to indicate the security status. Red lights may represent an alert or danger, while blue lights indicate a normal or safe condition.
* **Audible Feedback with the** [**Buzzer Module**](https://docs.acrome.net/electronics/add-on-modules/buzzer-module)

  The [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) emits a sound when the system detects a potential security threat, providing an audible alert to draw attention to the situation.

## **Step 2: Assemble**

**Getting Started**

1. **Hardware Setup**
   * Connect the SMD to the PC or Arduino board using [USB Gateway Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/gateway-modules/usb-gateway-module) or [Arduino Gateway Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/gateway-modules/arduino-gateway-module).
   * Connect the [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module), the [Buzzer Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/buzzer-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%2FHTElFBj0grEtNeNpafZf%2FSecurity%20System.png?alt=media&#x26;token=e4717611-7859-4f26-abb7-bf41e28eec52" alt=""><figcaption></figcaption></figure>

## Step 3: Run & Test

1. **Run the Application**
   * Execute the script, initiating the Security System application.
   * Observe the [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module) displaying colors and the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) emitting sound based on the detected distance.
2. **Customize Security Thresholds**
   * Adjust the predetermined distance threshold in the script to customize the security monitoring levels.
   * Experiment with different colors and sound patterns for the LED and buzzer to suit specific security scenarios.

## 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 *
import time

baudrate = 115200          # Baud rate of communication
ID = 0                     # ID of the SMD
buzzer_module_id = 5       # ID of the buzzer module
distance_sensor_id = 1     # ID of the ultrasonic distance sensor module
rgb_led_id = 5             # ID of the RGB LED 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 and initialize the USB port
    SerialPort = USB_Port()
    if not SerialPort:
        raise Exception("No compatible USB port found. Please check your connection.")

    # 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 distance data from the ultrasonic sensor
        distance = master.get_distance(ID, distance_sensor_id)  # Variable to store the distance data
        print(f"Distance: {distance} cm")                      # Print the value to observe

        if distance is not None:
            if distance < 15:
                # Activate the buzzer and set RGB LED to red
                master.set_buzzer(ID, buzzer_module_id, 600)          # Set buzzer frequency to 600 Hz
                master.set_rgb(ID, rgb_led_id, red=255, green=0, blue=0)  # Set LED to red
                time.sleep(0.5)                                       # Wait for half a second
                master.set_rgb(ID, rgb_led_id, red=0, green=0, blue=255)  # Change LED to blue
            else:
                # Deactivate the buzzer and turn off the RGB LED
                master.set_buzzer(ID, buzzer_module_id, 0)            # Turn off the buzzer
                master.set_rgb(ID, rgb_led_id, red=0, green=0, blue=0)  # Turn off the LED

        time.sleep(0.1)  # Delay for smooth operation

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

{% endcode %}
{% endtab %}

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

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

// Definitions
#define ID 0                   // ID of the SMD
#define BAUDRATE 115200         // Baud rate of communication
#define BUZZER_MODULE_ID 5      // ID of the buzzer module
#define DISTANCE_SENSOR_ID 1    // ID of the ultrasonic distance sensor module
#define RGB_LED_ID 5            // ID of the RGB LED module

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

void setup() {
    Serial.begin(BAUDRATE);  // Initialize serial communication
    master.begin();          // Start communication with the SMD
    master.scanModules();    // Scan and identify connected modules
}

void loop() {
    // Get distance data from the ultrasonic sensor
    int distance = master.getDistance(DISTANCE_SENSOR_ID);
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");

    if (distance > 0) {  // If a valid distance value is received
        if (distance < 15) {
            // Activate the buzzer and set RGB LED to red
            master.setBuzzer(BUZZER_MODULE_ID, 600);  // Set buzzer frequency to 600 Hz
            master.setRGB(RGB_LED_ID, 255, 0, 0);     // Set LED to red
            delay(500);  // Wait for half a second
            master.setRGB(RGB_LED_ID, 0, 0, 255);     // Change LED to blue
        } else {
            // Deactivate the buzzer and turn off the RGB LED
            master.setBuzzer(BUZZER_MODULE_ID, 0);
            master.setRGB(RGB_LED_ID, 0, 0, 0);
        }
    }

    delay(100);  // Delay for smooth operation
}
```

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