Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 2

Introduction

After following the steps in our previous post Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications and trying out the Adafruit TinyUSB Library Example serial_host_bridge it is now time for a more practical example. This example is going to show you how to connect real sensors to the Feather, read the values and have it command the BleuIO to advertise them.

Basically you could say that you are going to create a autonomous BLE beacon that advertise the current temperature, humidity etc.

For this example we are using a Gas sensor BME680 and a OPT3002 Light-to-Digital Sensor.

Requirements

Arduino Libraries

The libraries can easily be installed through the Arduino IDE:

  • Open Library Manager by clicking the Library Manager icon to the left or go through menu: Sketch>Include Libraries>Manage Libraries…
  • Search for Adafruit_BME680, and install the Adafruit_BME680 Library
  • Search for ClosedCube OPT3002, and install the ClosedCube OPT3002 library

Connecting I2C sensors

  • Connect four wires (at a minimum) for each I2C device.
  • Power the device with 3.3V, then a ground wire.
  • And a SCL clock wire, and and a SDA data wire.

Running the example

  • Make sure the BleuIO Dongle is connected to the Feather RP2040 Board.
  • Connect the Feather RP2040 Board to your computer using the USB cable.
  • Make sure the Feather RP2040 Board is selected aswell as the correct COM port in the dropdown menu.
  • (Optional) Change the frequency the sensors are read and advertising data updated, in the code
// How often we read the sensors and update the advertings message
(in seconds)
#define READ_UPDATE_FREQUENCY   5
  • Click the Upload button.

Done! The dongle should now be advertising the sensor values. (If you just plugged in the Feather it may take about 10 seconds before advertising starts as the BleuIO bootloader opens and closes)

  • (Optional) Open Serial Monitor. You can open the Serial Monitor from the menu: Tools>Serial Monitor

You should now see the output from the project.

Scanning the results

To see the results you can use any BLE scanner app.

Here we use nRF Connect:

The data in the red box is our sensor values:

0x006203EB001700170041

When we parse the hex into decimal values we get:

Light: 0x0062 = 98 uW/cm2
Pressure: 0x03EB = 1003 hPa
Temperature: 0x0017 = 23 Celcius
Humidity: 0x0017 = 23 %Rh
Gas Resistance: 0x0041 = 65 KOhms

Share this post on :

BleuIO Python Library Update (v1.4.0): Supports BleuIO Firmware v2.7.1

BleuIO Python library received a significant update to version 1.4.0, allows compatibility with BleuIO firmware v2.7.1. This update introduces several new commands, expanding the capabilities of BleuIO and helps developers to innovate further.

Enhanced Functionality: The latest BleuIO Python library update includes latest commands, aligning with the advancements in firmware v2.7.1. Let’s have a look into the key additions:

  1. at_autoexec(): This command corresponds to AT+AUTOEXEC in the BleuIO firmware. It enables developers to configure automatic execution of specific actions upon device boot-up. Whether it’s initializing connections or setting parameters, at_autoexec() enables the initialization process, enhancing the efficiency of BLE applications.
  2. at_clrautoexec(): This command corresponds to AT+CLRAUTOEXEC. It helps developers to clear the configured automatic execution settings on the BleuIO device. This function provides flexibility in modifying device behavior dynamically, ensuring seamless adaptability to changing project requirements.
  3. at_connparam(): BLE connection parameters play a pivotal role in defining the characteristics of data transmission between devices. The addition of at_connparam() facilitates precise control over connection parameters, helps developers to optimize communication efficiency based on specific use cases.
  4. at_getbond(): Security is paramount in BLE applications, especially concerning device bonding. The introduction of at_getbond() allows developers to retrieve bonding information from the BleuIO device, enabling seamless integration of security features and enhancing overall data integrity.

How to update: Updating to BleuIO Python library 1.4.0 is a straightforward process. Developers can leverage the command python -m pip install --upgrade bleuio to ensure they have access to the latest functionalities and optimizations.

Documentation and Further Details: Comprehensive details, usage examples, and guidelines to use the new functionalities introduced in version 1.4.0 of the BleuIO Python library is available at the official PyPI page https://pypi.org/project/bleuio/.

Share this post on :

Reading data from BLE device using Python, Microsoft Excel and BleuIO

In today’s data-driven world, extracting meaningful insights from raw data is crucial for informed decision-making. Microsoft Excel stands as an amazing tool for data analysis, offering powerful features for visualization, manipulation, and interpretation. However, accessing and processing data from external sources, such as BLE devices, can often be challenging and time-consuming.

BleuIO revolutionizes BLE application development with its intuitive AT command interface, eliminating the need for complex coding. With BleuIO, developers can communicate effortlessly with BLE devices, retrieve data, and execute commands with ease. Whether you’re a seasoned developer or just starting out, BleuIO streamlines the development process, allowing you to focus on innovation rather than technical complications. In this tutorial we will see how to read data from an air quality monitoring BLE device and get it on Microsoft excel sheet for further analysis.

What is BleuIO?

BleuIO is a versatile BLE 5.0 USB dongle designed to simplify the development of BLE applications. With its AT command interface, developers can easily communicate with BLE devices without the need for complex coding. Whether you’re a beginner or an experienced developer, BleuIO makes BLE application development faster and more accessible.

Setting Up the Environment

Before we dive into the code, let’s set up our development environment. You’ll need:

Communicating with BleuIO

To communicate with BleuIO, we’ll use Python and its serial library. First, ensure that you have the pyserial library installed. Then, connect BleuIO to your computer and identify the serial port it’s connected to. Next, we’ll send AT commands to BleuIO and retrieve the responses.

Here is the complete python code

import serial
import re
import json

# Define the serial port and baudrate
serial_port = "COM8"
baudrate = 57600


def read_response(ser):
    """
    Read response from serial port until a newline character is encountered.
    """
    response = b""
    while True:
        char = ser.read(1)
        if char == b"":
            break  # No more data to read
        response += char
        if char == b"\n\n":
            break  # Reached end of response
    return response.decode()


def hex_to_decimal(hex_str):
    """
    Convert hexadecimal string to decimal integer.
    """
    return round(int(hex_str, 16) / 10.0, 1)


def find_pattern(response):
    """
    Find and extract patterns matching the specified format.
    """
    pattern = r"\{T:\"(\w+)\",H:\"(\w+)\",PM1:\"(\w+)\"PM2\.5:\"(\w+)\"PM10:\"(\w+)\",IAQ:\"(\w+)\",PPM:\"(\w+)\"\}"
    matches = re.findall(pattern, response)
    return [
        {
            "T": hex_to_decimal(m[0]),
            "H": hex_to_decimal(m[1]),
            "PM1": hex_to_decimal(m[2]),
            "PM2.5": hex_to_decimal(m[3]),
            "PM10": hex_to_decimal(m[4]),
            # "IAQ": hex_to_decimal(m[5]),
            # "PPM": hex_to_decimal(m[6]),
        }
        for m in matches
    ]


def main():
    # Connect to the serial port
    ser = serial.Serial(serial_port, baudrate, timeout=1)

    # List to store responses
    responses = []

    # Send the command 'AT+CENTRAL' to the device
    ser.write(b"AT+CENTRAL\r")
    response = read_response(ser)

    # Connect to the device
    ser.write(b"AT+GAPCONNECT=[1]D1:53:C9:A9:8C:D2\r")
    response = read_response(ser)

    # Set notification
    ser.write(b"AT+SETNOTI=0021\r")
    response = read_response(ser)

    # Get all data
    ser.write(b"AT+GATTCWRITEWR=0021 GET DATA=ALL\r")
    while True:
        response = read_response(ser)
        responses.append(response.strip())
        if "DATA:END" in response:
            break  # End of response

    # Find and collect patterns matching the specified format
    collected_patterns = []
    for r in responses:
        pattern_matches = find_pattern(r)
        if pattern_matches:
            collected_patterns.extend(pattern_matches)

    # Convert to JSON
    json_data = json.dumps(collected_patterns, indent=2)
    print(json_data)

    # Close the serial port
    ser.close()


if __name__ == "__main__":
    main()

In this code we have

  • Establishes a connection to the serial port, sends commands to the BLE device, and retrieves responses of 7 days air quality data history stored in the device.
  • Parses the responses to extract relevant patterns using regular expressions.
  • Converts the extracted patterns into JSON format for easy handling and printing.
  • Finally, closes the serial port.

Integrating with Excel

Now, let’s integrate BleuIO with Excel to visualize and analyze the air quality data. By executing a Python script within Excel’s VBA environment, we can populate the data directly into Excel for further analysis.

Here is the complete code

Sub SerialCommunication()
    Dim response As String
    Dim pythonScriptPath As String
    Dim wsh As Object, exec As Object, output As String
    Dim jsonData As Object
    Dim obj As Object
    Dim i As Integer, j As Integer
    
    ' Set the path to the Python script
    pythonScriptPath = "C:\Users\PC\Desktop\excel bleuio\serial_communication.py" ' Update with the correct path
    
    ' Create Windows Script Host object
    Set wsh = CreateObject("WScript.Shell")
    
    ' Execute the Python script and capture its output
    Set exec = wsh.exec("python """ & pythonScriptPath & """")
    
    ' Read the output of the script
    output = exec.StdOut.ReadAll
    
    ' Parse JSON data
    Set jsonData = JsonConverter.ParseJson(output)
    
    ' Write headers in the first row
    i = 1 ' Starting row
    j = 1 ' Starting column
    For Each key In jsonData(1).Keys
        Sheet1.Cells(i, j).value = key
        j = j + 1
    Next key
    
    ' Write data into separate columns
    i = i + 1 ' Move to the next row
    For Each obj In jsonData
        j = 1 ' Starting column
        For Each key In obj.Keys
            Sheet1.Cells(i, j).value = obj(key)
            j = j + 1
        Next key
        i = i + 1 ' Move to the next row
    Next obj
End Sub

In this code we have,

  • Called the python script.
  • The response we got from python script we then passed it using JsonConverter.
  • Finally we loop through the object and presented it on the Excel sheet on their respective cells.


Set up JsonConverter

If you get error like JsonConverter object is not recognized, follow the steps:

  1. Download JSONConverter.bas: You can download the JSONConverter.bas file from various sources online. Here is a good github link to download from.
    https://github.com/VBA-tools/VBA-JSON
    It’s a common utility module for VBA that provides JSON parsing capability.
  2. Import JSONConverter.bas into your project: Open your Excel workbook, then go to the Visual Basic Editor (Alt + F11). From the menu, select File > Import File and choose the JSONConverter.bas file you downloaded. This will add the JSONConverter module to your project.
  3. Ensure Microsoft Scripting Runtime Reference: Go to Tools > References in the VBA editor and ensure that “Microsoft Scripting Runtime” is checked. This is needed for dictionary objects used in JSON parsing.

Run the script

  1. Insert a Button:
    • Go to the “Developer” tab in Excel. If you don’t see the “Developer” tab, you may need to enable it in Excel options.
    • Click on the “Insert” drop-down menu in the “Controls” group.
    • Choose the “Button” (Form Control) option.
    • Click and drag to draw the button on your worksheet.
  2. Assign the Macro:
    • Right-click on the button you just inserted and select “Assign Macro”.
    • In the “Assign Macro” dialog box, you should see a list of available macros. Since you just created a new macro, it should be listed. In this case, it should be “SerialCommunication”.
    • Select the “SerialCommunication” macro and click “OK”.
  3. Edit the Macro (if needed):
    • If you want to edit the macro, you can click on the “Edit” button in the “Assign Macro” dialog box. This will open the VBA editor where you can make changes to the macro.
  4. Test the Button:
    • Click on the button you inserted in your worksheet. This should trigger the “SerialCommunication” macro, which will execute the VBA code to communicate with the serial port and display the response in Excel.
  5. Ensure Correct Port and Settings:
    • Before testing, ensure that the COM port (COM8) and other settings in the VBA code match your requirements and device specifications.

Output

Use Cases: Transforming Data into Actionable Insights

  1. Indoor Air Quality Monitoring: Deploy BLE-enabled sensors in indoor environments to monitor air quality parameters such as temperature, humidity, and particulate matter. Excel’s data analysis capabilities enable users to identify trends, anomalies, and potential air quality issues, facilitating proactive measures for improving indoor air quality.
  2. Environmental Studies and Research: Conduct environmental studies and research projects using BleuIO to collect air quality data in various outdoor settings. Excel serves as a powerful tool for data aggregation, statistical analysis, and visualization, enabling researchers to gain valuable insights into environmental patterns and trends.
  3. Health and Safety Compliance: Ensure compliance with health and safety regulations by monitoring air quality in workplaces, public spaces, and industrial facilities. BleuIO, coupled with Excel, enables continuous monitoring of air quality parameters, facilitating compliance reporting and risk assessment processes.

By leveraging BleuIO’s seamless BLE communication capabilities and Excel’s robust data analysis features, developers and analysts can unlock the full potential of BLE application development and data analysis. Whether you’re monitoring air quality in indoor environments, conducting environmental research, or ensuring regulatory compliance, BleuIO and Excel provide a powerful combination for transforming raw data into actionable insights.

Share this post on :

BleuIO Firmware Update 2.7.0 Featuring Dynamic Connection Parameter Adjustment

BleuIO, the versatile Bluetooth Low Energy (BLE) USB dongle renowned for simplifying BLE application development, has released a new firmware upgrade to version 2.7.0. This latest update brings forth new features and commands, further enables developers to create innovative BLE applications with ease.

Added Features:

  • Dynamic Connection Parameter Adjustment: One of the standout additions in firmware 2.7.0 is the ability to change connection parameters on the fly, even while maintaining a connection. This feature not only facilitates fine-tuning of BLE connections but also provides flexibility in adapting to varying network conditions. Additionally, developers can modify default connection parameters for improved efficiency when utilizing the AT+GAPCONNECT command with just the MAC address as an argument.

New Commands:

  • AT+CONNPARAM: This command emerges as a powerful tool for setting or displaying preferred connection parameters. When executed while connected, it enables seamless updating of connection parameters on the current target connection, streamlining the optimization process for BLE applications.

With these enhancements, BleuIO offers rapid BLE development solution. Whether you’re a seasoned developer or pro in BLE applications development, firmware 2.7.0 unlocks new possibilities and simplifies the path to crafting cutting-edge solutions.

How to Upgrade:

To take advantage of these enhancements, make sure to update your BleuIO dongle to firmware version 2.7.0. You can find the firmware update and detailed instructions on the official BleuIO website. Click here to know more about firmware updates.

Share this post on :

Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications

In the realm of IoT projects, finding a reliable and efficient host hardware solution is important. The Adafruit Feather RP2040 is an excellent solution for that. It comes equipped with a comprehensive ecosystem, including an IDE and libraries tailored for your new projects. With this setup, you get to keep the main USB port for uploading, debugging, and data communication, while at the same time sending and receiving data to just-about-any USB device, like the BleuIO. 

https://learn.adafruit.com/adafruit-feather-rp2040-with-usb-type-a-host

In this first blog with the Adafruit Feather board, we are going to show how you can setup the USB stack and communicate with BleuIO using the Adafruit Feather RP2040 board. Later in next project we will show how to read a Temperature and Humidity sensor and display the data help of the Bluetooth Low Energy (BLE) interface. 

Requirements

Setting Up the Development Environment

Arduino IDE Download 

This section covers getting your Arduino IDE set up to include your board. 

  • Download and install it to your computer.
  • Once installed, open the Arduino IDE. In the Arduino IDE, and navigate to the Preferences window. 
  • Copy the following URL and Add the URL to the the Additional Boards Manager URLs field 
  • https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json 

Selecting the Appropriate Board Configuration

Add Board Support Package 

  • In the Arduino IDE, click on Tools > Board > Boards Manager. If you have previously selected a board, the Board menu item may have a board name after it. 
  • In the Boards Manager, search for RP2040. Scroll down to the Raspberry Pi Pico/RP2040 by Earle F Philhower, III entry. Click Install to install it. 

Choose Your Board 

  • In the Tools > Boards menu, you should now see Raspberry Pi RP2040 Boards (possibly followed by a version number). 
  • Navigate to the Raspberry Pi RP2040 Boards menu and choose Adafruit Feather RP2040 USB Host

Now you’re ready to begin using Arduino with your RP2040 board! The main use case for this Feather is to act as a USB host.  

Library Installation

Install Adafruit_TinyUSB Library 

To use your Feather as a USB host, you’ll need to install the Adafruit TinyUSB library. It can be installed using the Library Manager in the Arduino IDE. 

Click the Manage Libraries > menu item, search for Adafruit TinyUSB, and select the Adafruit TinyUSBLibrary 

 
Install Pico PIO USB Library 

Additionally, you’ll need to install the Pico PIO USB library.

Click the Manage Libraries > menu item again, search for PIO USB, and select the Pico PIO USB library.

Configuration and Deployment

Board Upload Settings 

  • In the Tools menu, select Adafruit Feather RP2040 USB Host under Board.
  • For CPU Speed, you’ll need to select 120 MHz or240 MHz.
  • Finally, under USB Stack, select Adafruit TinyUSB.  

Serial Host Bridge Example 

  • Load the example code onto your Feather after following the library installation instructions on the Arduino Library Install page
  • Navigate to the Adafruit TinyUSB Library Examples and select DualRole – CDC – serial_host_bridge 

Now you can control the BleuIO USB Dongle via the Adafruit Feather board. 

With these steps completed, you’re now ready to start integrating BleuIO with your Adafruit Feather RP2040 board. This setup lays the foundation for exciting IoT projects, and we’ll explore more functionalities in future tutorials where we will show how to make the BleuIO USB Dongle advertise data from a Temperature and Humidity sensor. 

Stay tuned for further guides on applying BleuIO and Adafruit Feather RP2040 for your projects!

Share this post on :

Using BleuIO for BLE Application Development with C++

In this tutorial, we will explore how to use BleuIO, a Bluetooth Low Energy (BLE) USB dongle, for developing BLE applications with C++. We’ll demonstrate how to connect to BleuIO via a serial port, send AT commands, and receive responses. Additionally, we’ll discuss the benefits of using BleuIO and provide some use cases for BLE application development with C++.

Introduction to BleuIO

BleuIO is a BLE USB dongle designed to simplify and accelerate the development of BLE applications. It provides a set of AT commands that allow developers to interact with BLE devices and services without having to write extensive code. By leveraging these AT commands, developers can quickly prototype and develop BLE applications with minimal effort.

Prerequisites

Before getting started, ensure you have the following:

  • BleuIO BLE USB dongle
  • Serial communication library for C++ (e.g., <iostream>, <unistd.h>, <fcntl.h>, <termios.h>)
  • Basic knowledge of C++ programming

Setting Up the Environment

First, connect the BleuIO dongle to your computer via USB. Then, (for MAC operating system) determine the serial port assigned to the dongle using the ls /dev/cu.* command in the terminal. Note down the serial port name (e.g., /dev/cu.usbmodem4048FDE52DAF1) as we’ll need it to establish a serial connection.

Writing the C++ Program

Below is a C++ program that connects to BleuIO, sends an AT command, and retrieves the response.

#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <chrono>
#include <thread>

int main() {
    // Open the serial port
    const char* portname = "/dev/cu.usbmodem4048FDE52DAF1"; // Change this to match your serial port
    int serial_port = open(portname, O_RDWR);
    if (serial_port < 0) {
        std::cerr << "Error opening serial port" << std::endl;
        return 1;
    }

    // Configure the serial port settings
    struct termios tty;
    tcgetattr(serial_port, &tty);
    cfsetospeed(&tty, B9600); // Set baud rate to 9600
    cfsetispeed(&tty, B9600);
    tty.c_cflag &= ~PARENB; // No parity
    tty.c_cflag &= ~CSTOPB; // 1 stop bit
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8; // 8 bits per byte
    tty.c_cflag &= ~CRTSCTS; // Disable hardware flow control
    tty.c_cflag |= CREAD | CLOCAL; // Enable reading and ignore control lines
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Raw input

    tcsetattr(serial_port, TCSANOW, &tty);

    // Write data to the serial port to put the dongle in central role
    const char* m1 = "AT+CENTRAL\r";
    write(serial_port, m1, strlen(m1));

    // Wait for 1 second to receive the response
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // Write data to the serial port to scan for nearby device for three seconds
    const char* m2 = "AT+GAPSCAN=3\r";
    write(serial_port, m2, strlen(m2));

    // Wait for 1 second to receive the response
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // Read response from the serial port with timeout
    char buf[1024];
    std::string response;
    int nbytes;
    fd_set fds;
    struct timeval timeout;
    FD_ZERO(&fds);
    FD_SET(serial_port, &fds);
    timeout.tv_sec = 3; // Timeout after 3 second
    timeout.tv_usec = 0;
    while (select(serial_port + 1, &fds, NULL, NULL, &timeout) > 0) {
        nbytes = read(serial_port, buf, sizeof(buf));
        if (nbytes < 0) {
            std::cerr << "Error reading from serial port" << std::endl;
            close(serial_port);
            return 1;
        }
        if (nbytes > 0) {
            response.append(buf, nbytes);
        }
    }

    // Display the response
    std::cout << "Response: " << response << std::endl;

    // Close the serial port
    close(serial_port);

    return 0;
}


Understanding the Code

  • We start by opening the serial port corresponding to BleuIO.
  • Next, we configure the serial port settings (baud rate, parity, stop bits, etc.) to match BleuIO’s communication parameters.
  • We then send the AT+CENTRAL command to BleuIO, which puts the dongle into central role.
  • After sending the command, we wait for 1 second to receive the response.
  • Then we send AT+GAPSCAN=3 to scan for nearby BLE devices for 3 seconds.
  • We read the response from the serial port with a timeout of 3 second.
  • Finally, we display the response received from BleuIO and close the serial port.

Output

Use Cases

BleuIO, with its AT command interface, presents an excellent starting point for developers looking to delve into Bluetooth Low Energy (BLE) application development with C++ across various domains.

Embedded Systems Development: BleuIO simplifies BLE application development in C++ for embedded systems. Developers can quickly prototype IoT devices, smart sensors, and wearables with BleuIO’s AT command interface, enabling features like remote control and wireless connectivity.

Cross-Platform Mobile Applications: Integrating BLE features into C++ mobile apps becomes seamless with BleuIO. Developers using frameworks like Qt or cross-platform tools can leverage BleuIO’s AT commands for device discovery, data exchange, and configuration across different platforms.

Industrial Automation and Control: C++ developers in industrial settings can enhance control systems and monitoring tools with BLE connectivity using BleuIO. Its AT command support enables communication with BLE-enabled equipment for tasks like remote monitoring and real-time data acquisition.

Educational Projects and Prototyping: BleuIO serves as an accessible platform for learning BLE technology with C++. Students and hobbyists can experiment with Bluetooth communication, protocol implementation, and IoT development, turning ideas into reality with minimal overhead.

In this tutorial, we’ve demonstrated how to use BleuIO for BLE application development with C++. By leveraging BleuIO’s AT commands, developers can streamline the development process and accelerate time-to-market for BLE-enabled projects. With the provided code and insights, you can now begin exploring BLE application development using BleuIO and C++ in your own projects.

For more information about BleuIO and its capabilities, refer to the official documentation and resources.

Share this post on :