DEV Community

Cover image for Real-Time BLE Proximity-Based LED Blinking with BleuIO: A Practical Guide
Bleuio tech
Bleuio tech

Posted on

Real-Time BLE Proximity-Based LED Blinking with BleuIO: A Practical Guide

BleuIO, a versatile BLE USB dongle, simplifies BLE application development with its powerful AT commands and cross-platform compatibility. This tutorial demonstrates how to use BleuIO with Python to build a real-time BLE proximity-based LED control system.

In this example, we focus on monitoring the RSSI (Received Signal Strength Indicator) of a specific BLE device and controlling the LED blinking rate of BleuIO based on proximity. The closer the device, the faster the blinking rate. The script also ensures clean termination, turning off the LED when the program exits.

This tutorial uses the BleuIO Python library to showcase a practical use case. However, the concepts can be implemented in any programming language.

Devices and Tools Needed

  1. BleuIO Pro BLE USB Dongle
  2. Python Installed (Python 3.6 or newer recommended)
  3. BleuIO Python Library Install the library using pip install bleuio
  4. Source Code Get the complete source code from GitHub: GitHub Repository

Use Case: Real-Time LED Blinking Based on Proximity

Objective:

  1. Continuously monitor the RSSI value of a specific BLE device.
  2. Adjust the LED blinking rate of the BleuIO dongle based on the device’s proximity.
  3. Ensure the LED turns off when the script is terminated.

Workflow:

  1. Scan for BLE devices: Identify the target device using its MAC address.
  2. Read RSSI values: Fetch real-time signal strength data.
  3. Control LED: Adjust the blinking rate based on proximity:
    • Very Close: Fast blinking.
    • Close: Moderate blinking.
    • Far: Slow blinking.
    • Very Far: Very slow blinking.
  4. Graceful Exit: Turn off the LED when the script ends.

The Python Script

Below is the complete script for this project:

import time
import json
import atexit
from bleuio_lib.bleuio_funcs import BleuIO

rssi_value = None
dongle = None  

def scan_callback(scan_input):
    global rssi_value  
    try:
        device_data = json.loads(scan_input[0])  
        if device_data.get("addr") == "[1]6B:C0:5C:BD:CF:14":
            rssi_value = device_data["rssi"]  
            print(f"\nDevice Found! Address: {device_data['addr']}, RSSI: {rssi_value}")
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

def send_led_command(dongle, rssi):
    if rssi is not None:  
        if rssi > -40:
            print(f"RSSI: {rssi} | Sending LED Command: 50/50")
            dongle.at_led(toggle="T", on_period="50", off_period="50")
        elif -60 <= rssi <= -40:
            print(f"RSSI: {rssi} | Sending LED Command: 100/100")
            dongle.at_led(toggle="T", on_period="100", off_period="100")
        elif -90 <= rssi < -60:
            print(f"RSSI: {rssi} | Sending LED Command: 200/200")
            dongle.at_led(toggle="T", on_period="200", off_period="200")
        else:
            print(f"RSSI: {rssi} | Sending LED Command: 300/300")
            dongle.at_led(toggle="T", on_period="300", off_period="300")
    else:
        print("No RSSI value available for LED command.")


def cleanup():
    if dongle:
        print("\n--- Turning off LED and cleaning up ---")
        dongle.at_led(0)

# Main logic
def main():
    global rssi_value, dongle  
    dongle = BleuIO()

    atexit.register(cleanup)

    dongle.register_scan_cb(scan_callback)

    print("\n--- Starting BLE Task ---\n")

    print("Setting device role to Central...")
    central_response = dongle.at_central()

    try:
        while True:
            print("\nStarting scan for 2 seconds...")
            dongle.at_gapscan(2)  
            time.sleep(3)  

            send_led_command(dongle, rssi_value)

            print("\nScan cycle completed. Restarting...\n")
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n--- Script Terminated by User ---")

# Run the main function
if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. Initialization: The script initializes the BleuIO dongle and sets it to Central role for scanning.
  2. Scan Callback: The scan_callback function extracts the RSSI value of the target device in real-time.
  3. LED Control: Based on the RSSI value:
    • RSSI > -40: Fast blinking (50ms on/off).
    • -60 <= RSSI <= -40: Moderate blinking (100ms on/off).
    • -90 <= RSSI < -60: Slow blinking (200ms on/off).
    • RSSI < -90: Very slow blinking (300ms on/off).
  4. Graceful Termination: The script turns off the LED when terminated with Ctrl + C.

Output

This example demonstrates how easy it is to use BleuIO for BLE applications. Whether you’re building proximity-based solutions or exploring BLE capabilities, BleuIO’s AT commands and Python library make it simple to get started.

Take this script, adapt it to your needs, and unlock the potential of BLE with BleuIO!

Top comments (0)