Introduction This project demonstrates how to integrate the Renesas EK-RA4M2 development board with the Renesas CO2 Sensor (RRH47000) and the new BleuIO Pro Dongle (SSD025) by Smart Sensor Devices, built on the Renesas Bluetooth Low Energy SoC DA14695. In this setup, the dongle advertises sensor data from the CO2 sensor, including CO2 concentration, humidity, and temperature.
The sensor data is displayed using the RTT Viewer.
Connect a Micro USB device cable (Type-A male to Micro-B male) between J10 (Debug1) on the EK-RA4M2 and a computer’s USB port.
Plug in the BleuIO Dongle using a USB OTG Cable (Type-A female to Micro-B male) and connect it to J11 (USB Full Speed).
Ensure that Jumper J12 is placed on pins 1-2.
Remove Jumper J15 pins.
Setting up PMOD1 The RRH47000 sensor connects via PMOD1. Since the sensor requires 5V, and PMOD by default provides 3.3V, some modifications are necessary:
For 5V the PMOD1 Config trace cut jumper E17 must be Short and E16 be Open. For I2C SCL E18 need to be Short and E14 need to be Open. For I2C SDA E19 need to be Short and E15 need to be Open.
The PMOD1 config can be found on the back of the RA4M2:
Importing the Project
Open e² studio IDE
Choose a workspace and click ‘Launch’
Download or clone the example project. Place the folder ‘bleuio_ra4m2_co2_monitor_example’ in workspace.
Choose Import Project
Select ‘Existing Projects into Workspace’ under the ‘General’ tab:
Click the ‘Browse…’ button and open folder where the ‘bleuio_ra4m2_co2_monitor_example’ project folder is located:
Finally select the project and click ‘Finish’. You have now imported the the project!
Running the Example
Build the project by clicking the building icon:
Use Debug to download and run the project. The first time you need to configure the debug settings. Click down arrow to the right of the Debug icon and select ‘Debug Configurations…’
Under ‘Renesas GDB Hardware Debugging’ select ‘bleuio_ra4m2_co2_monitor_example.elf’ and click ‘Debug’.
The debug is now configured and the ‘Debug’ icon can be used next time to run the project.
Open RTTViewer. Connect and use these settings:
Connection to J-Link: USB
Specify Target Device: R7FA4M2AD
Target Interface & Speed: SWD 4000kHz
RTT Control Block: Address 0x200009ac
On the debugger screen in e² studio click the ‘Resume’ icon twice to run the project.
The application is now running. When starting up you should notice all LEDs lighting up for one second then only the red LED will be on. It will turn off as soon as the BleuIO is configured and the green LED will turn on when advertising start.
You should now see the output on the RTTViewer.
Scanning the Dongle To view the advertised data, use an app like nRF Connect.
Decoding the Advertising Message The advertising data format is as follows:
020106: Default advertising flag for connectable devices.
09FF3600026E173E1D27: Manufacturer-specific data.
09: Message size.
FF: Manufacturer Specific Data flag.
3600: Renesas Manufacturer ID (little-endian).
026E: CO2 value in hex (622 in decimal).
173E: Temperature value, split into two bytes (23.62°C).
1D27: Humidity value, split into two bytes (29.39%).
This example serves as a foundational guide for integrating the Renesas EK-RA4M2 development board with a CO2 sensor and the BleuIO Pro Dongle for real-time monitoring. With its flexible setup, you can extend this project to suit your specific applications, such as real-time air quality monitoring, smart building systems, or other IoT-based environmental solutions. By leveraging the capabilities of the BleuIO Pro and Renesas platform, you can create robust, scalable solutions for your next Bluetooth Low Energy (BLE) project.
In today’s fast-paced world, flexibility and mobility in development are crucial. Whether you’re on the go or just want the convenience of working from your mobile device, having the ability to connect and interact with your development tools directly from your smartphone or tablet can be a game-changer. This article will guide you through a groundbreaking way to connect the BleuIO USB dongle to your mobile device using the Web Serial API. This tutorial will not only introduce you to the BleuIO dongle’s capabilities but also show you how to harness the power of BLE (Bluetooth Low Energy) on your mobile device with custom AT commands. By the end of this guide, you’ll be ready to run BLE scripts directly from your mobile browser, making BLE development more accessible and portable than ever.
Why This Matters
BleuIO is a versatile USB dongle that allows developers to easily add Bluetooth Low Energy (BLE) capabilities to their projects. Traditionally, connecting BLE devices to a mobile device required specialized apps or programming with platform-specific APIs. However, with the advent of the Web Serial API, it’s now possible to interact with BLE devices directly from a web browser, even on mobile devices. This means you can execute AT commands, scan for nearby BLE devices, and even build custom BLE applications right from your mobile browser.
This article is designed to help you leverage these capabilities, making BleuIO more accessible and useful whether you’re in the office, at home, or on the move. By following this tutorial, you’ll not only learn how to connect and communicate with BleuIO using your mobile device but also gain insight into how to integrate these features into your own BLE applications.
Getting Started: What You’ll Need
BleuIO USB Dongle: The star of this tutorial, a compact USB device that adds BLE functionality to any device with a USB port.
Mobile Device: A smartphone or tablet with a USB OTG (On-The-Go) adapter to connect the BleuIO dongle.
Web Browser: A modern web browser that supports the Web Serial API. For this tutorial, we’ll focus on Google Chrome for Android.
A Simple HTML/JavaScript Setup: We’ll walk through creating a basic web interface to send and receive AT commands from the BleuIO dongle.
Step 1: Setting Up Your Development Environment
Before diving into the code, let’s ensure your mobile device is ready. Here’s a quick checklist:
Connect BleuIO to Your Mobile Device: Use a USB OTG adapter to connect the BleuIO dongle to your smartphone or tablet.
Install a Compatible Browser: Ensure you have Google Chrome installed on your device. As of the time of writing, Chrome is one of the few mobile browsers that support the Web Serial API.
Step 2: Writing the Web Interface
Next, we’ll create a simple web interface that will allow you to connect to the BleuIO dongle, send AT commands, and display the responses. Below is the code we’ll use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Serial API with BleuIO</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous"
/>
<script type="module">
import { serial as webSerialPolyfill } from 'web-serial-polyfill@1.0.15';
// Use webSerialPolyfill as you would navigator.serial.
</script>
</head>
<body>
<div class="container mt-5">
<h1>BleuIO dongle Communication for Mobile browser</h1>
<br /><br />
<div class="row">
<div class="col-md-6">
<button id="connect" class="btn btn-success">
Connect to BleuIO
</button>
<button id="disconnect" class="btn btn-danger" style="display: none">
Disconnect
</button>
<br /><br /><br /><br />
<div id="command-section" style="display: none">
Basic command <br />
<button id="scanBtn" class="btn btn-primary">
Scan for nearby BLE devices (AT+GAPSCAN=3)
</button>
<br />
<br />
Write your own AT commands
<input
type="text"
id="inputData"
class="form-control"
placeholder="Write AT commands"
/><br />
<button id="send" class="btn btn-warning">Send</button>
</div>
</div>
<div class="col-md-6">
<h4>Output</h4>
<br />
<textarea
id="output"
style="height: 500px; width: 100%; border: 1px solid grey"
class="rounded p-4"
placeholder="Output will appear here..."
readonly
></textarea>
</div>
</div>
</div>
<script type="module" crossorigin>
import { serial as webSerialPolyfill } from 'https://cdn.jsdelivr.net/npm/web-serial-polyfill@1.0.15';
var serial_module = null;
if ('serial' in navigator) {
serial_module = navigator.serial;
} else {
if ('usb' in navigator) {
serial_module = webSerialPolyfill;
}
}
let port;
let reader;
const connectButton = document.getElementById('connect');
const disconnectButton = document.getElementById('disconnect');
const sendButton = document.getElementById('send');
const outputArea = document.getElementById('output');
const inputField = document.getElementById('inputData');
const commandSection = document.getElementById('command-section');
connectButton.addEventListener('click', async () => {
try {
port = await serial_module.requestPort();
await port.open({ baudRate: 9600 });
reader = port.readable.getReader();
// Hide connect button, show disconnect button and command section
connectButton.style.display = 'none';
disconnectButton.style.display = 'block';
commandSection.style.display = 'block';
while (true) {
const { value, done } = await reader.read();
if (done) {
reader.releaseLock();
break;
}
outputArea.value += new TextDecoder().decode(value);
}
} catch (error) {
console.error('Failed to connect:', error);
alert(
'Failed to connect to the device. Please try again.',
JSON.stringify(error)
);
}
});
disconnectButton.addEventListener('click', async () => {
try {
if (reader) {
reader.cancel();
reader = null;
}
if (port) {
await port.close();
port = null;
}
// Show connect button, hide disconnect button and command section
connectButton.style.display = 'block';
disconnectButton.style.display = 'none';
commandSection.style.display = 'none';
} catch (error) {
console.error('Failed to disconnect:', error);
alert('Failed to disconnect from the device. Please try again.');
}
});
sendButton.addEventListener('click', async () => {
outputArea.value = '';
const writer = port.writable.getWriter();
const dataToSend = inputField.value + '\r\n';
const data = new TextEncoder().encode(dataToSend);
await writer.write(data);
writer.releaseLock();
});
document.getElementById('scanBtn').addEventListener('click', async () => {
const writer = port.writable.getWriter();
let dataToSend = 'AT+CENTRAL' + '\r\n';
let data = new TextEncoder().encode(dataToSend);
await writer.write(data);
dataToSend = 'AT+GAPSCAN=3' + '\r\n';
data = new TextEncoder().encode(dataToSend);
await writer.write(data);
writer.releaseLock();
});
</script>
</body>
</html>
Step 3: Running the Script
Once your HTML file is ready, you can open it in your mobile browser. We have uploaded the script on github to try out.
Connect to BleuIO: Tap the “Connect to BleuIO” button to initiate a connection.
Send Commands: Once connected, you can start sending AT commands or use the built-in “Scan for BLE Devices” button to see nearby BLE devices.
View Output: The responses from the BleuIO dongle will appear in the output section on the right.
Step 4: Customizing and Expanding
This setup provides a solid foundation for more advanced BLE development on mobile devices. You can easily modify the script to add more AT commands or even build a full-fledged BLE application. Whether you want to control BLE devices, gather data, or create interactive applications, this setup offers flexibility and mobility.
Output:
With the BleuIO USB dongle and the Web Serial API, you can now bring BLE development to your mobile device, giving you the freedom to code, test, and interact with BLE devices wherever you are. This capability opens up new possibilities for developers who need to work on the go, providing a powerful toolset right in your pocket.
In an age where air quality has become increasingly important, monitoring CO2 levels in various environments is crucial. This project demonstrates how to create a real-time CO2 monitoring system using the Renesas EK-RA4M2 evaluation kit and the BleuIO dongle.
This project walks you through the process of scanning Bluetooth advertising signals from a HibouAir sensor, retrieving CO2 data, and responding to these readings with visual cues through LED indicators on the Renesas board. Blue LED for ‘good’ (<600ppm), green LED for ‘average’ (<1000ppm) and red LED for ‘poor’ (>1000ppm). The board will also print the CO2 values, as they change, on the RTTViewer.
Connect a Micro USB device cable (type-A male to micro-B male) between J10 (Debug1) and a Computer USB port.
Plug in a BleuIO Dongle in the USB OTG Cable (type-A female to micro-B male) and connect it to J11 (USB Full Speed).
Make sure Jumper J12 is placed on pins 1-2
Remove Jumper J15 pins
The example will make us of the on board LEDs R32 (Blue), R34 (Green) and R33 (Red):
Importing project
Open e² studio IDE
Choose a workspace and click ‘Launch’
Download or clone the example project. Place the folder ‘bleuio_ra4m2_co2_monitor_example’ in workspace.
Choose Import Project
Select ‘Existing Projects into Workspace’ under the ‘General’ tab:
Click the ‘Browse…’ button and open folder where the ‘bleuio_ra4m2_co2_monitor_example’ project folder is located:
Finally select the project and click ‘Finish’. You have now imported the the project!
Running the example
Go to file ‘usb_hcdc_app.c’ under ‘src/’ and edit line 56 to the board ID of the HibouAir Sensor:
#define BOARD_ID_TO_SCAN "2202B3"
The board ID is printed on the back of the HibouAir sensor:
Build the project by clicking the building icon:
Use Debug to download and run the project. The first time you need to configure the debug settings. Click down arrow to the right of the Debug icon and select ‘Debug Configurations…’
Under ‘Renesas GDB Hardware Debugging’ select ‘bleuio_ra4m2_co2_monitor_example.elf’ and click ‘Debug’.
The debug is now configured and the ‘Debug’ icon can be used next time to run the project.
Open RTTViewer. Connect and use these settings: Connection to J-Link: USB Specify Target Device: R7FA4M2AD Target Interface & Speed: SWD 4000kHz RTT Control Block: Address 0x2000095c
On the debugger screen in e² studio click the ‘Resume’ icon twice to run the project.
The application is now running. When starting up you should notice all LEDs lighting up for one second then only the red LED will be on. It will turn off as soon as the BleuIO is configured.
You should now see the output on the RTTViewer.
Output
When the CO2 value is less than 600 ppm only the blue LED will be turned on.
If it’s over 600 ppm but below 1000 ppm then the green LED will be on.
If it’s above 1000 ppm then the red LED will be on.
Practical Use Case
The BleuIO RA4M2 CO2 Monitor is an excellent example of how BLE technology can be harnessed to create practical, real-world applications. This project is particularly relevant for environments where air quality monitoring is essential, such as:
Offices and Workspaces: Monitor indoor air quality to ensure a healthy working environment, which can help in improving employee productivity and well-being.
Schools and Educational Institutions: Keep track of CO2 levels in classrooms to maintain a healthy atmosphere conducive to learning.
Public Buildings: Ensure that places with high foot traffic, like libraries or hospitals, maintain safe air quality levels for visitors.
Smart Homes: Integrate CO2 monitoring into home automation systems, allowing for better air quality control and energy efficiency.
With the BleuIO dongle and this project as a foundation, developers can easily expand on this concept, integrating additional sensors or creating custom applications tailored to specific needs. The combination of Bluetooth Low Energy and the versatile RA4M2 platform opens up a world of possibilities for creating innovative, responsive systems.
In this tutorial, we’ll guide you through creating a project that scans for nearby Bluetooth Low Energy (BLE) devices, filters them based on RSSI (Received Signal Strength Indicator), and determines if a specific device, the Close Beacon, is within a certain range. We’ll use the BleuIO USB dongle, which simplifies BLE development through its easy-to-use AT commands. By the end of this tutorial, you’ll have a working BLE scanner that can identify when the Close Beacon is within approximately 5 meters.
Overview of the Project
The goal of this project is to continuously scan for nearby BLE devices and check if a particular device, identified by its name (“Close beacon”), is within a defined range. We determine the range by setting an RSSI filter, which allows us to estimate the distance based on signal strength. If the device is found within this range, it is considered “online”; otherwise, it is “offline”.
Hardware Used
BleuIO USB Dongle: A BLE USB dongle that makes it easy to create BLE applications, prototypes, or test devices with AT commands and available libraries for Python and JavaScript.
Close Beacon: A BLE beacon device that broadcasts its presence to nearby BLE scanners. This hardware will be our target device to identify if it’s within a 5-meter range based on its RSSI.
Use Cases
Proximity Detection: Identify if a specific BLE device (e.g., a beacon or wearable) is within a set distance from the scanner.
Asset Tracking: Monitor the presence of assets in a particular area based on their BLE signal strength.
Environment Monitoring: Set up zones where certain devices must be present and get notified if they leave the range.
Getting Started with BleuIO
Before diving into the code, let’s cover the basic setup:
Hardware: You’ll need a BleuIO USB dongle. Plug it into your computer’s USB port.
Software: We’ll use JavaScript for this tutorial, running in a modern web browser that supports the Web Serial API. No additional software is required.
AT Commands Used
ATV1: Ensures verbose mode is enabled, meaning all command responses are returned in a human-readable format.
AT+CENTRAL: Sets the dongle into Central mode, allowing it to scan and connect to other BLE devices.
AT+FRSSI=-70: Filters out devices with an RSSI lower than -70 dBm, which helps to focus on devices within a closer range.
AT+GAPSCAN=3: Initiates a scan for nearby BLE devices.
HTML Setup
The following HTML file provides a simple user interface with a “Scan” button that starts the BLE scanning process.
This script, which is linked in the HTML file, manages the BLE scanning and RSSI filtering.
let port;
let reader;
let writer;
let buffer = '';
let ibeaconFound = false;
let scanIntervalId;
const connectButton = document.getElementById('connect');
const outputElement = document.getElementById('output');
connectButton.addEventListener('click', async () => {
try {
// Request a port and open a connection.
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
// Start reading from the serial port.
reader = port.readable.getReader();
writer = port.writable.getWriter();
// Send initial setup commands
await writer.write(new TextEncoder().encode('ATV1\r'));
await delay(1000);
await writer.write(new TextEncoder().encode('AT+CENTRAL\r'));
await delay(1000);
await writer.write(new TextEncoder().encode('AT+FRSSI=-70\r'));
await delay(1000);
// Start the scanning process at 15-second intervals
startScanInterval();
// Read data from the device.
readLoop();
} catch (error) {
console.error('There was an error opening the serial port:', error);
}
});
function startScanInterval() {
scanIntervalId = setInterval(async () => {
ibeaconFound = false; // Reset the flag for each scan
await writer.write(new TextEncoder().encode('AT+GAPSCAN=3\r'));
// Wait 3 seconds to check if 'Close beacon' is found
setTimeout(() => {
if (ibeaconFound) {
outputElement.innerHTML =
'<div style="color: green; display: inline-block; margin-right: 8px;">●</div>Close beacon is within the range of 5 meters.<br>';
} else {
outputElement.innerHTML =
'<div style="color: red; display: inline-block; margin-right: 8px;">●</div>Close beacon is not within the range of 5 meters.<br>';
}
}, 3000);
}, 15000); // 15 seconds interval
}
async function readLoop() {
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
// Convert the data to a string and append it to the buffer.
buffer += new TextDecoder().decode(value);
// Split the buffer by line breaks to process each line separately.
let lines = buffer.split('\n');
buffer = lines.pop(); // Save the last incomplete line for the next read.
for (let line of lines) {
line = line.trim(); // Remove any extra whitespace
// Check if the line is a valid JSON string
if (line.startsWith('{') && line.endsWith('}')) {
try {
// Parse the JSON object.
let data = JSON.parse(line);
// Check if the object contains the 'name' property and if it's "Sheikh ibeacon".
if (data.S && data.name === 'Close beacon') {
ibeaconFound = true;
}
} catch (e) {
console.error('Error parsing JSON:', e, line);
}
} else {
// Log non-JSON lines for debugging or just ignore them.
console.log('Non-JSON line received:', line);
}
}
}
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
window.addEventListener('beforeunload', async () => {
// Stop the scanning interval when the window is closed or refreshed.
if (scanIntervalId) {
clearInterval(scanIntervalId);
}
// Close the port when the window is closed or refreshed.
if (reader) {
await reader.cancel();
reader.releaseLock();
}
if (writer) {
writer.releaseLock();
}
if (port) {
await port.close();
}
});
Code Explanation
HTML Interface:
The HTML file provides a simple user interface with a “Scan” button. When clicked, this button triggers the BLE scanning process.
JavaScript Code:
Initialization: We start by requesting access to the serial port and opening a connection to the BLE dongle. After setting up the port, we configure the dongle by sending the ATV1, AT+CENTRAL, and AT+FRSSI=-70 commands. These commands enable verbose mode, set the device to central mode, and filter out weak BLE signals (below -70 dBm), respectively.
Scan Interval: The setInterval function initiates a BLE scan every 15 seconds. The AT+GAPSCAN=3 command scans for nearby BLE devices for 3 seconds.
Device Detection: After each scan, we check if the specific BLE device named “Close beacon” is found. If it is, a green dot appears with a message indicating the device is within range. If not, a red dot with a message indicating the device is not within range is shown.
Reading Data: The readLoop function continuously reads data from the serial port. It checks for JSON-formatted responses from the dongle and looks for the device name in the scanned results.
Clean Up: We ensure that the scanning process stops and the serial port is closed when the user leaves the page or closes the window.
Setting Up RSSI Filtering for 5-Meter Range Detection
In this project, the goal was to detect if a specific BLE device, “Close Beacon,” is within approximately 5 meters of our BLE dongle. We achieved this by using the Received Signal Strength Indicator (RSSI), which helps us estimate the distance based on the strength of the received signal.
Understanding RSSI and Distance
RSSI is a measure of signal strength, with higher (less negative) values indicating a closer proximity to the BLE device. The relationship between RSSI and distance is governed by the following formula:
A: RSSI at 1 meter (typically around -56 dBm for Bluetooth).
n: Path-loss exponent (usually 2 for free space, 3 for indoor environments).
For a 5-meter distance, we calculated that an RSSI of -70 dBm is appropriate. Using the formula:
A = -56 dBm
n = 2 (assuming a free-space environment)
An RSSI of -70 dBm corresponds to approximately 5 meters, which is suitable for detecting if a device is within this range.
Practical Distance Adjustment
While theoretical calculations are useful, it’s also possible to perform a practical distance adjustment by placing the “Close Beacon” 5 meters away from the BLE dongle in a controlled environment, such as a room. You can then read the obtained RSSI value directly from the BleuIO dongle. This approach takes into account the real-world radio performance of both devices, providing a more accurate and practical RSSI value for your specific setup.
Output
The BleuIO USB dongle makes it incredibly easy to develop and prototype BLE applications using AT commands. This project demonstrates how you can set up a BLE scanner with RSSI filtering to monitor the proximity of a specific device. Whether you’re developing a custom IoT solution, monitoring assets, or just exploring BLE technology, BleuIO provides a simple and effective toolset to get your projects up and running quickly.
By following this tutorial, you should now have a good understanding of how to use the BleuIO dongle to create a BLE application that scans for devices and filters them based on their signal strength.
This project demonstrates how to leverage the Renesas RA4M2 microcontroller, combined with the BleuIO Bluetooth Low Energy (BLE) USB dongle, to perform a wireless signal strength scan. It provides a practical example of how to use the USB Host Communication Device Class (HCDC) driver to communicate with a BLE device, highlighting how easy it is to create BLE applications using the BleuIO dongle.
By integrating these technologies, the project enables users to scan for nearby BLE devices, parse the Received Signal Strength Indicator (RSSI) from advertising data, and display it in real-time using the RTTViewer. This setup offers a hands-on approach to understanding BLE communication and signal strength analysis.
Connect a Micro USB device cable (type-A male to micro-B male) between J10 (Debug1) and a Computer USB port.
Plug in a BleuIO Dongle in the USB OTG Cable (type-A female to micro-B male) and connect it to J11 (USB Full Speed).
Make sure Jumper J12 is placed on pins 1-2
Remove Jumper J15 pins
Importing project
Open e² studio IDE
Choose a workspace and click ‘Launch’
Download or clone the example project. Place the folder ‘bleuio_ra4m2_rssi_scan_example’ in workspace.
Choose Import Project
Select ‘Existing Projects into Workspace’ under the ‘General’ tab:
Click the ‘Browse…’ button and open folder where the ‘bleuio_ra4m2_rssi_scan_example’ project folder is located:
Finally select the project and click ‘Finish’. You have now imported the the project!
Running the example
Go to file ‘usb_hcdc_app.c’ under ‘src/’ and edit line 54 to the mac address of the desired:
#define ADDR_TO_SCAN "[0]D0:76:50:80:01:75"
[0] = public address
[1] = private address
On a closebeacon the mac address is printed on the back of the box (it will need to be converted to Hex):
For example: 208-118-080-128-001-117 in Hex is: D0-76-50-80-01-75
Build the project by clicking the building icon:
Use Debug to download and run the project. The first time you need to configure the debug settings. Click down arrow to the right of the Debug icon and select ‘Debug Configurations…’
Under ‘Renesas GDB Hardware Debugging’ select ‘bleuio_ra4m2_rssi_scan_example.elf’ and click ‘Debug’. The debug is now configured and the ‘Debug’ icon can be used next time to run the project.
Open RTTViewer. Connect and use these settings:
Connection to J-Link: USB Specify Target Device: R7FA4M2AD Target Interface & Speed: SWD 4000kHz RTT Control Block: Address 0x2000095c
On the debugger screen in e² studio click the ‘Resume’ icon twice to run the project.
You should now see the output on the RTTViewer. Notice that when you move the scanned device closer to the BleuIO the RSSI value will increase.
Output
Below is the output screen that displays the RSSI values in real-time as the BleuIO dongle scans for nearby BLE devices:
Practical Use Cases
The BleuIO RA4M2 RSSI Scan Project can be applied in various scenarios where monitoring BLE signal strength is critical:
Proximity-Based Applications: By tracking RSSI values, developers can create proximity-based applications where actions are triggered based on the distance between BLE devices, such as automated check-ins, asset tracking, or location-based services.
Signal Strength Mapping: The project can be used to map signal strength in different environments, helping to optimize the placement of BLE devices like beacons in smart homes, retail stores, or industrial settings.
Device Tracking and Monitoring: In IoT applications, RSSI can be used to monitor the presence and movement of devices within a specific range, useful in security systems, inventory management, or environmental monitoring.
This project not only showcases the capabilities of the BleuIO dongle but also serves as a foundation for developing more complex BLE applications. Whether you’re a hobbyist, developer, or engineer, this project provides valuable insights into BLE communication and its practical applications.
In this tutorial, we will walk you through the steps to get started with Bluetooth Low Energy (BLE) development using the BleuIO USB dongle and the Go programming language. BleuIO is a versatile and user-friendly BLE USB dongle that simplifies BLE application development with its easy-to-use AT Commands. We will show you how to set up your environment, write a simple Go program to interact with the BLE dongle, and explore some of the key features of BleuIO.
Introduction to Go
Go, also known as Golang, is an open-source programming language developed by Google. It is designed for simplicity, efficiency, and reliability, making it an excellent choice for system programming and large-scale software development. Go’s strong concurrency support, fast compilation, and robust standard library make it a popular language for network programming, cloud services, and, of course, BLE applications.
Introduction to BleuIO
BleuIO is a Bluetooth Low Energy USB dongle that can be used to create new BLE applications quickly and easily. With its built-in AT Commands, developers can interact with the BLE dongle without needing deep knowledge of BLE protocols or complex configurations. BleuIO supports various operating systems, making it a versatile tool for any development environment.
Key features of BleuIO include:
Easy-to-use AT Commands for faster development
Compatibility with any programming language
Support for Windows, macOS, and Linux
Setting Up Your Development Environment
Step 1: Install Go
First, ensure that you have Go installed on your system. You can download the latest version of Go from the official website: https://golang.org/dl/. Follow the installation instructions for your operating system.
Step 2: Initialize a New Go Module
Create a directory and open a terminal . Run the following command to initialize a new Go module:
go mod init bleuio-example
Step 3: Install the Serial Package
Install the go.bug.st/serial package, which provides a simple API for serial communication in Go:
go get go.bug.st/serial
Writing Your First Go Program with BleuIO
Step 4: Write the Program
Create a new file named main.go in your project directory and add the following code:
package main
import ( "fmt" "log" "time"
"go.bug.st/serial" )
func main() { // Open the serial port mode := &serial.Mode{ BaudRate: 9600, } port, err := serial.Open("/dev/cu.usbmodem4048FDE52CF21", mode) if err != nil { log.Fatalf("Failed to open port: %v", err) } defer port.Close()
// Write "AT+CENTRAL" to the serial port _, err = port.Write([]byte("AT+CENTRAL\r")) if err != nil { log.Fatalf("Failed to write AT+CENTRAL to port: %v", err) } fmt.Println("Command sent: AT+CENTRAL")
// Wait for a short moment to ensure the command is processed time.Sleep(2 * time.Second)
// Read the response for the AT+CENTRAL command buf := make([]byte, 100) n, err := port.Read(buf) if err != nil { log.Fatalf("Failed to read from port: %v", err) } fmt.Printf("Response from AT+CENTRAL:\n%s\n", string(buf[:n]))
// Write "AT+GAPSCAN=5" to the serial port _, err = port.Write([]byte("AT+GAPSCAN=5\r")) if err != nil { log.Fatalf("Failed to write AT+GAPSCAN=5 to port: %v", err) } fmt.Println("Command sent: AT+GAPSCAN=5")
// Wait for the scan to complete (5 seconds in this case) time.Sleep(6 * time.Second) // Adding a bit more time to ensure the response is received
// Read the response for the AT+GAPSCAN=5 command buf = make([]byte, 1000) n, err = port.Read(buf) if err != nil { log.Fatalf("Failed to read from port: %v", err) }
// Print the response fmt.Printf("Response from AT+GAPSCAN=5:\n%s\n", string(buf[:n])) }
Step 5: Run the Program
Ensure your BleuIO USB dongle is connected and configured correctly. Then, run the program using the following command in the terminal:
go run main.go
Explanation of the Program
Opening the Serial Port: The program opens the serial port where the BleuIO dongle is connected. Adjust the serial port path (/dev/cu.usbmodem4048FDE52CF21) according to your system (e.g., COM3 on Windows). To get the location of connected BleuIO on macOS, run this command on terminal ls /dev/cu.*
Setting the Central Role: The program sends the AT+CENTRAL command to set the BLE dongle in central role mode. Similarly we can try sending AT+FINDSCANDATA=5B07=3 which will look for advertised data from BLE devices whose manufacturing id is 5B07.
Reading the Response: It waits for 2 seconds to ensure the command is processed and reads the response from the serial port.
Scanning for BLE Devices: The program sends the AT+GAPSCAN=5 command to scan for nearby BLE devices for 5 seconds.
Printing the Scan Results: After waiting for the scan to complete, the program reads and prints the response from the serial port.
Output
This tutorial demonstrated how to get started with BLE development using the BleuIO USB dongle and the Go programming language. BleuIO simplifies BLE application development with its straightforward AT Commands, making it accessible for developers using any programming language. With Go’s efficiency and robust standard library, you can quickly develop powerful BLE applications.
In this tutorial, we’ll walk you through the process of creating your own Apple HomeKit accessory that monitor and manage air quality data from a BLE device, specifically the HibouAir air quality monitoring device. By the end of this tutorial, you’ll have a functional BLE application that integrates with Apple’s HomeKit, demonstrating how easily you can develop BLE applications with the BleuIO dongle.
Overview of the Project
In this project, our goal is to create a BLE application that communicates with the HibouAir device, which provides air quality data. The application will:
Connect to a BleuIO USB dongle to communicate with BLE devices.
Scan for the HibouAir device using AT commands.
Decode the air quality data from the HibouAir device.
Integrate with HomeKit to display and manage the data in a smart home environment.
Update the accessory information and continuously monitor the air quality data.
What is HomeKit?
HomeKit is Apple’s framework for home automation that allows users to control smart home devices using their Apple devices. With HomeKit, you can control a wide range of devices like lights, thermostats, locks, and sensors through the Apple Home app, Siri voice commands, and other Apple devices.
The key features of HomeKit include:
Secure Communication: HomeKit uses end-to-end encryption to ensure that data transmitted between your devices and the Home app remains private and secure.
Integration with Siri: HomeKit-enabled devices can be controlled using Siri voice commands, enabling hands-free control of your smart home.
Automation: Users can create automated routines and scenes that trigger actions based on time, location, or device status. For example, you can set up a “Good Night” scene that turns off the lights and locks the door when you say goodnight to Siri.
What is HAP-NodeJS?
HAP-NodeJS is an open-source implementation of the HomeKit Accessory Protocol (HAP) written in Node.js. It allows developers to create HomeKit-compatible accessories and bridge devices that can be controlled through Apple’s HomeKit ecosystem.
Devices Required
To follow this tutorial, you will need:
BleuIO USB Dongle: A Bluetooth Low Energy USB dongle used to interface with BLE devices.
HibouAir Device: A BLE air quality monitoring device that provides air quality metrics such as temperature, CO2 levels, humidity, and light levels.
A Computer: Running Windows, macOS, or Linux , Raspberry Pi or any other platform that can run Node.js.
Connecting to BleuIO
To connect to the BleuIO dongle, we’ll use Node.js and the serialport package to communicate with the BLE device. The BleuIO dongle interfaces with your computer over a serial port, which allows you to send AT commands and receive data from BLE devices.
Decoding the Data
Once we receive the data from the HibouAir device, we need to decode it. The data is encoded in a specific format that we will parse and extract the relevant air quality metrics. We use a function to decode the advertisement data, which includes temperature, CO2 levels, humidity, and light levels.
Setting Up HomeKit Environment Data
We will use the hap-nodejs library to integrate our application with HomeKit. This will allow us to create HomeKit accessories that represent our air quality metrics. We set up services for temperature, CO2 levels, humidity, and light, and update these services with real-time data from the HibouAir device.
Running the Script
Here’s a step-by-step guide on how to set up and run the script:
Install Required Packages First, make sure you have Node.js installed on your computer. Then, install the required npm packages by running npm install hap-nodejs serialport
Create the Script Save the following code as hibouair.js or clone it from https://github.com/smart-sensor-devices-ab/bleuio-hibouair-homekit-integration
const hap = require('hap-nodejs');
const { SerialPort } = require('serialport');
const Accessory = hap.Accessory;
const Characteristic = hap.Characteristic;
const CharacteristicEventTypes = hap.CharacteristicEventTypes;
const Service = hap.Service;
// Get the device ID from the command-line arguments
const deviceId = process.argv[2];
if (!deviceId) {
console.error(
'Device ID not present. Please provide the device ID as follows:'
);
console.error('node hibouair.js <device_id>');
process.exit(1);
}
// Define the manufacturer name you're looking for
const targetManufacturer = 'Smart Sensor Devices';
// Buffers to hold the incoming data
let buffer = '';
let scanningDetected = false;
let responseFound = false;
let port; // Variable to hold the SerialPort instance
// Initialize HomeKit accessories globally
let temperature, co2, humidity, light;
async function connectAndSendCommands() {
try {
// Get a list of all serial ports
const ports = await SerialPort.list();
// Find the port with the specified manufacturer
const targetPort = ports.find(
(port) => port.manufacturer === targetManufacturer
);
if (!targetPort) {
console.log(`No port found with manufacturer: ${targetManufacturer}`);
return;
}
// Log the selected port
console.log(`Connecting to port: ${targetPort.path}`);
// Create a new SerialPort instance for the selected port
port = new SerialPort({
path: targetPort.path,
baudRate: 9600, // Adjust the baud rate as needed
});
// Event handler for when the port opens
port.on('open', () => {
console.log(
`Port ${targetPort.path} is open and ready for communication.`
);
// Write the initial command
port.write('AT+CENTRAL\r\n', (err) => {
if (err) {
console.error('Error writing initial command:', err.message);
} else {
console.log('Initial command sent: AT+CENTRAL');
}
});
// Start the periodic scanning for BLE data
setInterval(() => {
port.write(`AT+FINDSCANDATA=${deviceId}=5\r\n`, (err) => {
if (err) {
console.error('Error writing scan command:', err.message);
} else {
console.log(`Scan command sent: AT+FINDSCANDATA=${deviceId}=5`);
}
});
}, 20000); // 20000 milliseconds = 20 seconds
});
// Event handler for when data is received on the port
port.on('data', (data) => {
buffer += data.toString();
processBuffer();
});
// Event handler for when there is an error
port.on('error', (err) => {
console.error('Error:', err.message);
if (port) {
port.close(() => {
console.log('Port closed due to error.');
});
}
});
} catch (err) {
console.error('Error listing or connecting to serial ports:', err);
if (port) {
port.close(() => {
console.log('Port closed due to error.');
});
}
}
function processBuffer() {
// Split the buffer into lines
const lines = buffer.split('\r\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === 'SCANNING...') {
scanningDetected = true;
} else if (line === 'SCAN COMPLETE') {
scanningDetected = false;
} else if (scanningDetected && line.length > 0) {
// Extract the data from the line
const dataMatch = line.match(/^\[.*?\] Device Data \[ADV\]: (.+)$/);
if (dataMatch && dataMatch[1]) {
const extractedData = dataMatch[1].trim();
console.log('Extracted data:', extractedData);
// Decode the data
const decodedData = advDataDecode(extractedData);
console.log('Decoded data:', decodedData);
responseFound = true;
buffer = ''; // Clear the buffer after finding the response
if (!temperature || !co2 || !humidity || !light) {
setupAccessory(decodedData); // Setup accessory if not already done
} else {
updateAccessory(decodedData); // Update accessory with decoded data
}
return;
}
}
}
// Keep the remaining buffer if no relevant line was found
buffer = lines[lines.length - 1]; // Retain the last part of the buffer
}
// Function to decode the advertisement data
function advDataDecode(adv) {
let pos = adv.indexOf('5B0705');
let dt = new Date();
let currentTs =
dt.getFullYear() +
'/' +
(dt.getMonth() + 1).toString().padStart(2, '0') +
'/' +
dt.getDate().toString().padStart(2, '0') +
' ' +
dt.getHours().toString().padStart(2, '0') +
':' +
dt.getMinutes().toString().padStart(2, '0') +
':' +
dt.getSeconds().toString().padStart(2, '0');
let tempHex = parseInt(
'0x' +
adv
.substr(pos + 22, 4)
.match(/../g)
.reverse()
.join('')
);
if (adv) dataShowing = true;
if (tempHex > 1000) tempHex = (tempHex - (65535 + 1)) / 10;
else tempHex = tempHex / 10;
return {
boardID: adv.substr(pos + 8, 6),
type: adv.substr(pos + 6, 2),
light: parseInt(
'0x' +
adv
.substr(pos + 14, 4)
.match(/../g)
.reverse()
.join('')
),
pressure:
parseInt(
'0x' +
adv
.substr(pos + 18, 4)
.match(/../g)
.reverse()
.join('')
) / 10,
temp: tempHex,
hum:
parseInt(
'0x' +
adv
.substr(pos + 26, 4)
.match(/../g)
.reverse()
.join('')
) / 10,
voc: parseInt(
'0x' +
adv
.substr(pos + 30, 4)
.match(/../g)
.reverse()
.join('')
),
pm1:
parseInt(
'0x' +
adv
.substr(pos + 34, 4)
.match(/../g)
.reverse()
.join('')
) / 10,
pm25:
parseInt(
'0x' +
adv
.substr(pos + 38, 4)
.match(/../g)
.reverse()
.join('')
) / 10,
pm10:
parseInt(
'0x' +
adv
.substr(pos + 42, 4)
.match(/../g)
.reverse()
.join('')
) / 10,
co2: parseInt('0x' + adv.substr(pos + 46, 4)),
vocType: parseInt('0x' + adv.substr(pos + 50, 2)),
ts: currentTs,
};
}
}
// Function to setup HomeKit accessory
function setupAccessory(data) {
const accessoryUuid = hap.uuid.generate('hap.hibouair.sensor');
const accessory = new Accessory('HibouAir', accessoryUuid);
// Create a function to initialize services
function initializeService(
serviceType,
serviceName,
initialValue,
characteristicType
) {
const service = new serviceType(serviceName);
const characteristic = service.getCharacteristic(characteristicType);
characteristic.on(CharacteristicEventTypes.GET, (callback) => {
console.log(`Queried current ${serviceName}: ${initialValue}`);
callback(undefined, initialValue);
});
accessory.addService(service);
return {
service,
characteristic,
initialValue,
};
}
// Initialize temperature, CO2, humidity, and light services
temperature = initializeService(
Service.TemperatureSensor,
'Temperature Sensor',
data.temp,
Characteristic.CurrentTemperature
);
co2 = initializeService(
Service.CarbonDioxideSensor,
'CO2 Sensor',
data.co2,
Characteristic.CarbonDioxideLevel
);
humidity = initializeService(
Service.HumiditySensor,
'Humidity Sensor',
data.hum,
Characteristic.CurrentRelativeHumidity
);
light = initializeService(
Service.LightSensor,
'Light Sensor',
data.light,
Characteristic.CurrentAmbientLightLevel
);
// Set accessory information
accessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, 'Smart Sensor Devices')
.setCharacteristic(Characteristic.SerialNumber, deviceId);
// Publish the accessory
accessory.publish({
username: '17:51:07:F4:BC:8B',
pincode: '123-45-678',
port: 47129,
category: hap.Categories.SENSOR, // value here defines the symbol shown in the pairing screen
});
console.log('Accessory setup finished!');
}
// Function to update HomeKit accessory with new data
function updateAccessory(data) {
temperature.initialValue = data.temp;
co2.initialValue = data.co2;
humidity.initialValue = data.hum;
light.initialValue = data.light;
console.log(`Updated current temperature: ${temperature.initialValue}`);
console.log(`Updated current CO2 level: ${co2.initialValue}`);
console.log(`Updated current Humidity level: ${humidity.initialValue}`);
console.log(`Updated current light level: ${light.initialValue}`);
// Update the characteristic values
temperature.service.setCharacteristic(
Characteristic.CurrentTemperature,
temperature.initialValue
);
co2.service.setCharacteristic(
Characteristic.CarbonDioxideLevel,
co2.initialValue
);
humidity.service.setCharacteristic(
Characteristic.CurrentRelativeHumidity,
humidity.initialValue
);
light.service.setCharacteristic(
Characteristic.CurrentAmbientLightLevel,
light.initialValue
);
}
// Call the function to connect and send commands
connectAndSendCommands();
Run the Script
Execute the script from your terminal by providing the device ID as an argument:
node hibouair.js 220069
This command will start the script, connect to the BleuIO dongle, scan for the HibouAir device, decode the data, and set up the HomeKit accessories with the real-time data from the device.
Output
Screenshot
This tutorial demonstrates how easy it is to develop BLE applications using BleuIO and integrate them with HomeKit. By following these steps, you can create real-time monitoring solutions for a variety of BLE-enabled devices, enhancing the functionality of your smart home environment.
This example is going to showcase how to connect a PDM MEMS Microphone to a Adafruit Feather RP2040, together with a BlueIO to create a background noise sensor that measures and advertisises the current sound level in decibel (dB). This example is very similar to Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 2 but instead of reading sensor data over SPI every few seconds, we’re using the arduino PDM interface to continuously fill a buffer with data then everytime the buffer is full we’re going to translate the data into the current sound level in dB. The buffer size of 8000 bytes (2 bytes per sample) and the sample rate of 16kHz means we record 250ms each time we fill the buffer.
Connect four wires from the PDM Microphone (3V, GND, DAT, CLK) to the following pins on the Feather Board:
3V to 3.3V to power the device, then GND to GND.
And CLK to SCL, and DAT to SDA.
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 as well as the correct COM port in the drop-down menu.
(Optional) Change the frequency the advertising message is updated with the dB value, in the code // How often we update the advertising message (in seconds) #define READ_UPDATE_FREQUENCY 1
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: 0x0032
When we parse the hex into decimal values we get: 0x0032 = 50 dB
In this tutorial, we’ll explore how to create a Bluetooth Low Energy (BLE) application using ReactJS and the BleuIO BLE USB dongle. BleuIO is a versatile BLE device that makes developing BLE applications fast and easy with its user-friendly AT commands.
Introduction
Bluetooth Low Energy (BLE) technology is widely used for short-range communication, particularly in IoT applications. BleuIO, with its easy-to-use AT commands, simplifies the process of integrating BLE functionality into your applications. In this tutorial, we’ll demonstrate how to create a BLE application using ReactJS. Specifically, we will show you how to scan for nearby BLE devices for three seconds and display the results on the screen, highlighting the capabilities of BleuIO.
Prerequisites
Before we start, make sure you have the following:
A computer with a Chromium-based browser (like Chrome or Edge)
Node.js and npm installed
Basic knowledge of ReactJS
Setting Up the Project
First, let’s create a new React project. If you haven’t already installed create-react-app, you can do so with the following command:
npx create-react-app ble-react-app cd ble-react-app npm start
This will create a new React application and start the development server.
Creating the Serial Port Component
We’ll create a component to handle the serial port communication with the BleuIO dongle. Create a new file called SerialPortComponent.jsin the src directory and add the following code:
import React, { useState, useEffect } from 'react';
// Read data from the serial port. readSerialData(reader); } catch (error) { console.error('There was an error opening the serial port:', error); } };
const readSerialData = async (reader) => { try { while (true) { const { value, done } = await reader.read(); if (done) { // Allow the serial port to be closed later. reader.releaseLock(); break; } // Convert the received data to a string and update the state. setOutput((prevOutput) => prevOutput + value); } } catch (error) { console.error('Error reading from the serial port:', error); } };
// Wait for scan to complete and read response await new Promise((resolve) => setTimeout(resolve, 3000));
// Read and process data from the serial port let scanData = ''; while (true) { const { value, done } = await reader.read(); if (done) { break; } scanData += value; } setOutput((prevOutput) => prevOutput + scanData); } else { console.error('Writer not available'); } } catch (error) { console.error('Error writing to the serial port:', error); } };
useEffect(() => { return () => { // Cleanup function to close port when component unmounts if (port) { port.close(); } if (reader) { reader.releaseLock(); } if (writer) { writer.releaseLock(); } }; }, [port, reader, writer]);
return ( <div className="mt-5"> <button className="btn btn-success me-2" onClick={connectToSerialPort} disabled={!!port} > Connect to BleuIO </button> <button className="btn btn-warning me-2" onClick={writeToSerialPort} disabled={!writer} > Scan for nearby BLE devices for 3 seconds </button>
{output && ( <div> <h3>Response from the BleuIO:</h3> <pre>{output}</pre> </div> )} </div> ); };
export default SerialPortComponent;
Explanation of the Code
Connecting to the Serial Port: The connectToSerialPort function requests access to the serial port and opens a connection. It initializes the text encoder and decoder streams for reading and writing data.
Reading Serial Data: The readSerialData function reads data from the serial port continuously and updates the output state with the received data.
Writing to the Serial Port: The writeToSerialPort function sends AT commands to the serial port. It first sends the AT+CENTRAL command to put the device in central mode, then sends the AT+GAPSCAN=3 command to scan for nearby BLE devices for 3 seconds. It reads and displays the response from the serial port after the scan completes.
Cleanup: The useEffect hook ensures that the serial port is properly closed and resources are released when the component is unmounted.
Using the Component in Your App
Update your App.js to include the new SerialPortComponent.
// src/App.js import React from 'react'; import SerialPortComponent from './SerialPortComponent';
function App() { return ( <div className="App"> <header className="App-header"> <h1>BLE Application with React and BleuIO</h1> <SerialPortComponent /> </header> </div> ); }
export default App;
Running the Application
Make sure your BleuIO USB dongle is connected to your computer. Start your React application:
npm start
Open your browser and navigate to http://localhost:3000. You should see the application with two buttons: “Connect to BleuIO” and “Scan for nearby BLE devices for 3 seconds“.
Connect to BleuIO: Click this button to connect to the BleuIO USB dongle. The browser will prompt you to select the serial port.
Scan for nearby BLE devices for 3 seconds: After connecting, click this button to send the AT+CENTRAL and AT+GAPSCAN=3 commands to the BleuIO dongle. The output area will display the response from the device.
Output
In this tutorial, we’ve demonstrated a basic usage of BleuIO AT commands by creating a BLE application using ReactJS and the BleuIO USB dongle. By leveraging the Web Serial API and the straightforward AT commands provided by BleuIO, you can quickly develop BLE applications that run on any platform. You can expand on this example to develop your own applications using BleuIO’s comprehensive set of AT commands. Read more about the AT commands in our documentation.
BleuIO simplifies BLE development and, combined with the popularity and versatility of ReactJS, allows developers to create powerful and cross-platform BLE applications with ease. Whether you’re building IoT devices, wearable tech, or any BLE-enabled application, BleuIO is a reliable and efficient choice.
Building on the steps in our previous post Integrating BleuIO with Adafruit Feather RP2040 for Seamless BLE Applications Part 2 where we showed how to use the BleuIO to advertise sensor data, we are now going to put the data in a Custom Service. Additionally, we are going to protect the data by making it only available with a secure connection that can only be established by entering a 6-digit passkey.
This example is going to show you how to start protecting your data as well as how to set up and use a custom service.
// How often we read the sensors and update the characteristics (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.
Getting the data
To get the results you can use any BLE scanner app. Here we use nRF Connect:
Find the device that advertise as BleuIO Arduino Example and connect.
You will be prompted to pair.
And then to enter the passkey. Enter the passkey/pin (default: 232425) and continue.
Go to the service with the UUID: ee6ec068-7447-4045-9fd0-593f3ba3c2ee Notice that you are now bonded.
The service has 5 characteristics, one for each of the sensor values:
1. Lux 2. Pressure 3. Temperature 4. Humidity 5. Gas resistance
Read and/or enable notification for each characteristic to see the data. The Characteristic User Description Descriptor of each characteristic can be read to show what value it holds.
Like in the previous example, when we parse the hex into decimal values we get: