Sensor data collection from STM32 and SHT85 using Bluetooth Low Energy

The project is showcasing a simple way of using the the BleuIO Dongle to advertise data that the STM32 reads from a sensor which is connected to the STM32 Nucleo-144.

Requirments :

  • A BleuIO dongle (https://www.bleuio.com/)
  • A SHT85 sensor (https://sensirion.com/products/catalog/SHT85/)
  • A board with a STM32 Microcontroller with a USB port. (A Nucleo-144 development board: NUCLEO-H743ZI2, was used developing this example. (https://www.st.com/en/evaluation-tools/nucleo-h743zi.html)
  • To connect the dongle to the Nucleo board we used a “USB A to Micro USB B”-cable with a USB A female-to-female adapter.)
  • STM32CubeIDE (https://www.st.com/en/development-tools/stm32cubeide.html)

When the BleuIO Dongle is connected to the Nucleo boards USB port, the STM32 will recognize it and start advertising the sensor values that it reads from the SHT85 along with the sensor serial number. It will update these values every 10 seconds.

Setup the project

Part 1 : Download the project

Get project HERE

https://github.com/smart-sensor-devices-ab/stm32_bleuio_SHT85_example

Either clone the project, or download it as a zip file and unzip it, into your STM32CubeIDE workspace.

Part 2 : Importing as an Existing Project

From STM32CubeIDE choose File>Import…

Then choose General>Existing Projects into Workspace then click ‘Next >’

Make sure you’ve choosen your workspace in ‘Select root directory:’

You should see the project “stm32_bleuio_SHT85_example”, check it and click ‘Finish’.

If you download the project as a zip file you will need to rename the project folder from ‘stm32_bleuio_SHT85_example-master’ to ‘stm32_bleuio_SHT85_example’

Connect the SDA to PF0 on the Nucleo board and SCL to PF1.

Then setup I2C2 in the STM32Cube ioc file like this:

Running the example

In STMCubeIDE click the hammer icon to build the project.

  • Open up the ‘STMicroelectronics STLink Viritual COM Port’ with a serial terminal emulation program like TeraTerm, Putty or CoolTerm.

Baudrate: 115200

Data Bits: 8

Parity: None

Stop Bits: 1

Flow Control: None

  • In STMCubeIDE click the green play button to flash and run it on your board. The first time you click it the ‘Run Configuration’ window will appear. You can just leave it as is and click run.
  • Connect the BleuIO Dongle.

Access sensor data from a web browser

We wrote a simple script that connects to the BleuIO dongle and reads advertised data from STM32.

For this script to work, we need

Steps

Create a simple Html file called index.html which will serve as the frontend of the script. This Html file contains some buttons that help connect and read advertised data from the remote dongle, which is connected to stm32.

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Bootstrap CSS -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />

    <title>STM32 Read sensor value</title>
  </head>
  <body>
    <div class="container mt-5">
      <h1>Sensor data collection from stm32 using Bluetooth Low Energy</h1>
      <button id="connect" class="btn btn-primary">Connect</button>
      <button id="getdata" class="btn btn-success">Get device data</button>
      <div id="loader"></div>
      <br />
      <div id="response" class="fw-bold"></div>

      <script src="./index.js"></script>
    </div>
  </body>
</html>

Create a js file called script.js and include it at the bottom of the Html file. This js file uses the BleuIO js library to write AT commands and communicate with the other dongle.

import * as my_dongle from 'bleuio'

//connect to BleuIO
document.getElementById('connect').addEventListener('click', function(){
  my_dongle.at_connect()
})
//get sensor data
document.getElementById('getdata').addEventListener('click', function(){
  document.getElementById('loader').innerHTML = 'Loading'
  //set the BleuIO dongle into dual role
    my_dongle.at_dual().then(()=>{
      // sensor id of the device that we are trying to get data from
      let sensorID='05084FA3'

      //look for advertised data of with the sensor id
        my_dongle.at_findscandata(sensorID,4).then(x=>{        

          //split the advertised data from the respnse
          let advdata= x[x.length-1].split(" ").pop()

          //trim the advertised string to only get sensor response
          const result = advdata.split(sensorID).slice(1).join(sensorID) 

          //get temperature and humidity value
          let temp = result.substring(0, 4);
          let hum = result.substring(4, 8);

          //convert from hex to decimal and device by 100
          temp = parseInt(temp, 16)/100
          hum = (parseInt(hum, 16)/100).toFixed(1)  

          document.getElementById('loader').innerHTML = ''
          document.getElementById('response').innerHTML = `Sensor ID : 05084FA3 <br/>
          Temperature : ${temp} °C<br/>
          Humidity : ${hum} %rH<br/>`              
        })
    })
    
  })

The script js file has two button actions; connect and read advertised data.

We also need to update the Sensor ID on line 13 of script js. The Sensor ID of this example project is 05084FA3, which we got from SHT85.

Therefore this script looks for advertised data that contains sensor ID 05084FA3. After getting advertised data , we split the temperature and humidity information and show it on our index.html page.

Now we need a web bundler. We can use parcel.js

Once parcel js installed, lets go to the root directory and type “parcel index.html”. This will start our development environment.

Lets open the script on a browser and select the right port where the dongle is connected.

The web script is available on web script folder of the GitHub repository.

Share this post on :

Plotting real-time graph from Bluetooth device using C#

Bluetooth Low Energy (BLE) is a low power wireless technology used to connect devices. It is a popular communication method, especially in the Internet of Things era. Several devices around the house have a built-in Bluetooth transceiver, and most of them provide useful capabilities to automate jobs. This technology is widely used in the healthcare, fitness, beacons, security, and home entertainment industries. For that reason, it is really interesting to create a desktop application using C# that plot a real-time graph of values from HibouAir – Air Quality Monitor using BleuIO.

For this project, Bluetooth Low Energy USB dongle called BlueIO is used, which will act as a central device to retrieve data. HibouAir will serve as a peripheral device to transmit the data. The is simple to use and can be used for other purposes such as showing real-time air quality data; temperate, humidity, pressure, particle matters etc.

Let’s start

First, let’s create a new project in visual studio and select C# windows form application from the list.

Choose a suitable name for your project.

Once the project is created, we will see a blank form screen where we will add buttons and labels to communicate with BleuIO graphically and show plot real-time values from HibouAir.

The application will connect to the BleuIO dongle to its given COM port from the script. You can change the port easily by going to line number 19.

We will have a disconnect button to disconnect BleuIO from the COM port.

By clicking on the Get data button, the script will connect to The BleuIO dongle and put it on DUAL mode. Then it will look for scanned data and filter out the device advertised information that we are looking for. You can change the scanForDevice value on line number 24.

Once it starts fetching data, it will go through a parser that decodes the advertised data and returns a meaningful number. 

In this script, we are only showing how to plot Ambient Light Sensor (ALS) value in lux and plot it on the chart.

The form will look like this.

The .cs file associated with this will have the following code.
Source code is available at https://github.com/smart-sensor-devices-ab/bluetooth_realtimedata_csharp

using System;
using System.Windows.Forms;
using System.IO.Ports;
using LiveCharts;
using LiveCharts.Configurations;
using LiveCharts.Wpf;
using System.Threading;
using System.Collections;
using System.Linq;
using System.Text;
using Timer = System.Windows.Forms.Timer;

namespace ConstantChanges
{
    public partial class ConstantChanges : Form
    {
        //Connect to Serial port
        //Replace port number to your comport
        SerialPort mySerialPort = new SerialPort("COM7", 57600, Parity.None, 8, StopBits.One);
        //string ScannedData = "";
        string ScannedData = "";
        bool clicked = false;

        public string scanForDevice = "5B07050345840D";
        int chartYval ;

        public String ParseSensorData(string input)
        {
            int counter = 17;
            int pressureData = Convert.ToInt32(input[counter + 9].ToString() + input[counter + 10].ToString() + input[counter + 7].ToString() + input[counter + 8].ToString(), 16);
            chartYval = pressureData;

            return pressureData.ToString();

        }
        public ConstantChanges()
        {
            InitializeComponent();
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
            mySerialPort.Open();
            ArrayList device = new ArrayList();
            //To handle live data easily, in this case we built a specialized type
            //the MeasureModel class, it only contains 2 properties
            //DateTime and Value
            //We need to configure LiveCharts to handle MeasureModel class
            //The next code configures MEasureModel  globally, this means
            //that livecharts learns to plot MeasureModel and will use this config every time
            //a ChartValues instance uses this type.
            //this code ideally should only run once, when application starts is reccomended.
            //you can configure series in many ways, learn more at http://lvcharts.net/App/examples/v1/wpf/Types%20and%20Configuration

            var mapper = Mappers.Xy<MeasureModel>()
                .X(model => model.DateTime.Ticks)   //use DateTime.Ticks as X
                .Y(model => model.Value);           //use the value property as Y

            //lets save the mapper globally.
            Charting.For<MeasureModel>(mapper);

            //the ChartValues property will store our values array
            ChartValues = new ChartValues<MeasureModel>();
            cartesianChart1.Series = new SeriesCollection
            {
                new LineSeries
                {
                    Values = ChartValues,
                    PointGeometrySize = 18,
                    StrokeThickness = 4
                }
            };
            cartesianChart1.AxisX.Add(new Axis
            {
                DisableAnimations = true,
                LabelFormatter = value => new System.DateTime((long)value).ToString("mm:ss"),
                Separator = new Separator
                {
                    Step = TimeSpan.FromSeconds(1).Ticks
                }
            });

            SetAxisLimits(System.DateTime.Now);

            //The next code simulates data changes every 500 ms
            Timer = new Timer
            {
                Interval = 3000
            };
            Timer.Tick += TimerOnTick;
            R = new Random();
            Timer.Start();
        }

        //Store response from the dongle
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            SerialPort sp = (SerialPort)sender;
            string s = sp.ReadExisting();

            //get advertised data
            if (s.Contains("[ADV]"))
            {
                ScannedData = s;
            }

        }

        public ChartValues<MeasureModel> ChartValues { get; set; }
        public Timer Timer { get; set; }
        public Random R { get; set; }

        private void SetAxisLimits(System.DateTime now)
        {
            cartesianChart1.AxisX[0].MaxValue = now.Ticks + TimeSpan.FromSeconds(1).Ticks; // lets force the axis to be 100ms ahead
            cartesianChart1.AxisX[0].MinValue = now.Ticks - TimeSpan.FromSeconds(8).Ticks; //we only care about the last 8 seconds
        }

        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            var now = System.DateTime.Now;
            if(clicked == true) {
                getBleData();
            }
            
            ChartValues.Add(new MeasureModel
            {
                DateTime = now,
                //Value = R.Next(0, 10)
                Value = chartYval
            });

            SetAxisLimits(now);            
            //lets only use the last 30 values
            if (ChartValues.Count > 30) ChartValues.RemoveAt(0);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void cartesianChart1_ChildChanged(object sender, System.Windows.Forms.Integration.ChildChangedEventArgs e)
        {

        }

        //Get data every 3 seconds
        private void getBleData()
        {
            var inputByte = new byte[] { 13 };
            byte[] dualCmd = Encoding.UTF8.GetBytes("AT+DUAL");
            dualCmd = dualCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(dualCmd, 0, dualCmd.Length);
            Thread.Sleep(500);
            byte[] gapScanCmd = Encoding.UTF8.GetBytes("AT+FINDSCANDATA="+ scanForDevice);
            gapScanCmd = gapScanCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(gapScanCmd, 0, gapScanCmd.Length);
            Thread.Sleep(1200);
            byte[] bytes = Encoding.UTF8.GetBytes("\u0003");
            bytes = bytes.Concat(inputByte).ToArray();
            mySerialPort.Write(bytes, 0, bytes.Length);

            if (ScannedData != null)
            {
                sensor_op.Text = ScannedData;
                string lastWord = ScannedData.Split(' ').Last();
                if(lastWord !=null) {
                    var toPrint = ParseSensorData(lastWord);
                    sensor_op.Text = "Current Value :" + toPrint;
                }
                
                
            }
        }


        private void btnGetData_Click(object sender, EventArgs e)
        {
            var inputByte = new byte[] { 13 };
            byte[] dualCmd = Encoding.UTF8.GetBytes("AT+DUAL");
            dualCmd = dualCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(dualCmd, 0, dualCmd.Length);
            Thread.Sleep(500);
            byte[] gapScanCmd = Encoding.UTF8.GetBytes("AT+FINDSCANDATA="+ scanForDevice);
            gapScanCmd = gapScanCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(gapScanCmd, 0, gapScanCmd.Length);
            Thread.Sleep(1200);
            byte[] bytes = Encoding.UTF8.GetBytes("\u0003");
            bytes = bytes.Concat(inputByte).ToArray();
            mySerialPort.Write(bytes, 0, bytes.Length);

            if (ScannedData!=null) {
                sensor_op.Text = ScannedData;
                string lastWord = ScannedData.Split(' ').Last();
                if (lastWord != null)
                {
                    var toPrint = ParseSensorData(lastWord);
                    sensor_op.Text = "Current Value :"+toPrint;
                }
                clicked = true;
            }  
            //Show Chart
            cartesianChart1.Visible = true;
        }
    }
}

As you can notice, I wrote COM7 to connect to the serial port because the BleuIO device on my computer is connected to COM7.

You can check your COM port from the device manager. 

Also, scanForDevice value is 5B07050345840D where 45840D is the device id. 

Let’s run the project and click on Get Data. You will notice a new light value is plotting in every three seconds.

Here is a demo of this sample application. 

Share this post on :

C# Desktop application to get real-time BLE data from Air Quality Sensor

Bluetooth Low Energy (BLE) is a low power wireless technology used to connect devices. It is a popular communication method, especially in the Internet of Things era. Several devices around the house have a built-in Bluetooth transceiver, and most of them provide useful capabilities to automate jobs. This technology is widely used in the healthcare, fitness, beacons, security, and home entertainment industries. For that reason, it is really interesting to create a desktop application using C# that access BLE device data around the house.

In this example, we will create a simple C# windows form application to get real-time HibouAir environmental data using BleuIO. 

This script can be used to connect and view other BLE devices data.

Let’s start

First, let’s create a new project in visual studio and select C# windows form application from the list.

Choose a suitable name for your project.

Once the project is created, we will see a blank form screen where we will add buttons and labels to communicate with BleuIO graphically.


The application will connect to the BleuIO dongle to its given COM port from the script. You can change the port easily by going to line number 18.
We will have a disconnect button to disconnect BleuIO from the COM port.

The button Scan for HibouAir devices will look for nearby HibouAir devices and store them in an Array. The Combobox (dropdown item) next to it will load the stored device from where we can select a device to get its data.


The Get data button will show the real-time environmental data of this device.

The form will look like this.

The .cs file associated to this will have the following code.

Source code is available at https://github.com/smart-sensor-devices-ab/bluetooth_realtimedata_csharp

using System;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;


namespace WindowsFormsApp1
{
    

    public partial class Form1 : Form
    {
        //Connect to Serial port
        //Replace port number to your comport
        SerialPort mySerialPort = new SerialPort("COM18", 57600, Parity.None, 8, StopBits.One);
        ArrayList device = new ArrayList();
        string ScannedData = "";
        public string selectedDevices = "";
        string advData = "";

        // HibouAir Advertise data decrypt and show output
        public String ParseSensorData(string input)
        {
            int counter = 17;
            string theData = " SensorID : " + input[counter + 1] +
              input[counter + 2] +
              input[counter + 3] +
              input[counter + 4] +
              input[counter + 5] +
              input[counter + 6] + "\n\n " +
              "Pressure : " + Convert.ToInt32(input[counter + 13].ToString() + input[counter + 14].ToString() + input[counter + 11].ToString() + input[counter + 12].ToString(), 16) / 10 + " mbar\n\n " +
              "Temperature : " + Convert.ToInt32(input[counter + 17].ToString() + input[counter + 18].ToString() + input[counter + 15].ToString() + input[counter + 16].ToString(), 16) / 10 + " °C\n\n " +
              "Humidity : " + Convert.ToInt32(input[counter + 21].ToString() + input[counter + 22].ToString() + input[counter + 19].ToString() + input[counter + 20].ToString(), 16) / 10 + " %rH\n\n " +
              "VOC : " + Convert.ToInt32(input[counter + 25].ToString() + input[counter + 26].ToString() + input[counter + 23].ToString() + input[counter + 24].ToString(), 16) / 10 + "\n\n " +
              "ALS : " + Convert.ToInt32(input[counter + 9].ToString() + input[counter + 10].ToString() + input[counter + 7].ToString() + input[counter + 8].ToString(), 16) + " Lux\n\n " +
              "PM 1.0 : " + Convert.ToInt32(input[counter + 29].ToString() + input[counter + 30].ToString() + input[counter + 27].ToString() + input[counter + 28].ToString(), 16) / 10 + " µg/m³\n\n " +
              "PM 2.5 : " + Convert.ToInt32(input[counter + 33].ToString() + input[counter + 34].ToString() + input[counter + 31].ToString() + input[counter + 32].ToString(), 16) / 10 + " µg/m³\n\n " +
              "PM 10 : " + Convert.ToInt32(input[counter + 37].ToString() + input[counter + 38].ToString() + input[counter + 35].ToString() + input[counter + 36].ToString(), 16) / 10 + " µg/m³"
              ;

            sensor_op.Text = theData.ToString();
            return theData;
        }


        public Form1()
        {
            InitializeComponent();    
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
            mySerialPort.Open();
            ArrayList device = new ArrayList();

        }

        
        //Store response from the dongle
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
            SerialPort sp = (SerialPort)sender;
            string s = sp.ReadExisting();
            if (s.Contains("RSSI") && s.Contains("(HibouAIR)") )
            {
                device.Add(s);
                
            }
            if (selectedDevices != "")
            {
                label1.Invoke(new EventHandler(delegate { label1.Text = selectedDevices.Remove(0, 3); })); 
           
                if (s.Contains("[ADV]"))
                {
                    ScannedData=s;
                    
                   // output_data.Invoke(new EventHandler(delegate { output_data.Text += "TT: " + s + "\r\n"; }));
                }           
             }
            //output_data.Invoke(new EventHandler(delegate { output_data.Text += s + "\r\n"; }));


            //lbl_output.Invoke(this.myDelegate, new Object[] { s });
        }


       
        // Disconnect from COM port
        private void btn_disconnect_Click(object sender, EventArgs e)
        {
            mySerialPort.Close();
            Environment.Exit(0);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }



        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void btn_deviceList_Click(object sender, EventArgs e)
        {
            var inputByte = new byte[] { 13 };
            byte[] dualCmd = Encoding.UTF8.GetBytes("AT+DUAL");
            dualCmd = dualCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(dualCmd, 0, dualCmd.Length);

            byte[] gapScanCmd = Encoding.UTF8.GetBytes("AT+GAPSCAN=2");
            gapScanCmd = gapScanCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(gapScanCmd, 0, gapScanCmd.Length);
            

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        // Load devices on dropdown
        private void dropdown_device_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(dropdown_device.Text == "Load Devices")
            {
                
                foreach (var a in device)
                {
                    dropdown_device.Items.Add(a);
                }
            }
            else
            {
                selectedDevices = dropdown_device.Text;
                string[] selectedDeviceID = selectedDevices.Split(' ');
                selectedDevices = selectedDeviceID[2];
                btnGetData.Visible = true;
            }
            
        }

        //get advertised data of selected device
        private void btnGetData_Click(object sender, EventArgs e)
        {


            var inputByte = new byte[] { 13 };
            byte[] gapScanCmd = Encoding.UTF8.GetBytes("AT+FINDSCANDATA=FF5B07");
            gapScanCmd = gapScanCmd.Concat(inputByte).ToArray();
            mySerialPort.Write(gapScanCmd, 0, gapScanCmd.Length);
            Thread.Sleep(500);
            byte[] bytes = Encoding.UTF8.GetBytes("\u0003");
            bytes = bytes.Concat(inputByte).ToArray();
            mySerialPort.Write(bytes, 0, bytes.Length);
            var array = ScannedData.Split('\n');
            int i = 0;
            //filter selected device data
            foreach (var a in array)
            {
                string kk = (string)a;
                if (kk.Contains(selectedDevices.Remove(0, 3)))
                {
                    var bleData = array[i].Split(' ');
                    advData = bleData[4];

                    var toPrint = ParseSensorData(advData);

                    break;
                }

                i++;

            }
            
        }
    }

    
}

As you can notice, I wrote COM18 to connect to the serial port because the BleuIO device on my computer is connected to COM18.
You can check your COM port from the device manager.
Let’s run the project and click on scan for HibouAir devices.

Here is a demo of this sample application.

Share this post on :

Multiple Connections in Bluetooth LE Central Device

Bluetooth low energy technology offers a suitable way of connecting smart devices. The term IoT or Internet of Things brings new technologies to transform and make the world in the era of connectivity. The IoT says that everything is connected, and Bluetooth has made it much easier to work. One central device can initiate and maintain connections with multiple Bluetooth Low Energy peripherals devices. 

The BleuIO is a Bluetooth low energy solution that can create new BLE 5.0 applications fastest and easiest way. Using this BleuIO’s multi-connection feature, we can easily connect to multiple BLE devices and transfer data between them.

This article will explain how to use BleuIO’s multi-connection features, connect to multiple BLE devices and transfer data between them. We will use three BleuIO dongles for this project: one central and two peripheral. The central dongle will connect to peripheral and send data simultaneously. 

We will create a simple python script that will help us do the task.

Requirements :

  1. 3 pcs BleuIO Dongle.
  2. Python 2.7 or Python 3.4 and newer
  3. pyserial 3.5

Task:

Step 1: 

Let’s create a python file called py_serial_transfer.py and copy the following code.

Source code is also available at GitHub

https://github.com/smart-sensor-devices-ab/ble_multi_connection_example.git
import serial
import time
import string
import random

target_dongle_mac_address = (
    "[0]40:48:FD:E5:2D:AF"  # Change this to the 1st peripheral's mac address.
)
target_dongle_mac_address2 = (
    "[0]40:48:FD:E5:2D:B5"  # Change this to the 2nd peripheral's mac address.
)
your_com_port = "COM7"  # Change this to the com port your dongle is connected to.

connecting_to_dongle = True
trying_to_connect = False
trying_to_connect2 = False

def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

print("Connecting to dongle...")
# Trying to connect to dongle until connected. Make sure the port and baudrate is the same as your dongle.
# You can check in the device manager to see what port then right-click and choose properties then the Port Settings
# tab to see the other settings
while connecting_to_dongle:
    try:
        console = serial.Serial(
            port=your_com_port,
            baudrate=57600,
            parity="N",
            stopbits=1,
            bytesize=8,
            timeout=0,
        )
        if console.is_open.__bool__():
            connecting_to_dongle = False
    except:
        print("Dongle not connected. Please reconnect Dongle.")
        time.sleep(5)

print("Connected to Dongle.")

connected = "0"
connected2 = "0"
while 1 and console.is_open.__bool__():
    console.write(str.encode("AT+DUAL"))
    console.write("\r".encode())
    time.sleep(0.1)
    print("Putting dongle in Dual role and trying to connect to other dongle.")
    while connected == "0":
        time.sleep(0.5)
        if not trying_to_connect:
            console.write(str.encode("AT+GAPCONNECT="))
            console.write(str.encode(target_dongle_mac_address))
            console.write("\r".encode())
            trying_to_connect = True
        dongle_output2 = console.read(console.in_waiting)
        time.sleep(2)
        print("Trying to connect to Peripheral 1...")
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected = "1"
                print("Connected to 1st device!")                
                time.sleep(5)
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected = "0"
                print("Disconnected!")
                trying_to_connect = False
            dongle_output2 = " "
    while connected2 == "0":
        time.sleep(0.5)
        if not trying_to_connect2:
            console.write(str.encode("AT+GAPCONNECT="))
            console.write(str.encode(target_dongle_mac_address2))
            console.write("\r".encode())
            trying_to_connect2 = True
        dongle_output2 = console.read(console.in_waiting)
        time.sleep(2)
        print("Trying to connect to Peripheral 2...")
        if not dongle_output2.isspace():
            if dongle_output2.decode().__contains__("\r\nCONNECTED."):
                connected2 = "1"
                print("Connected to 2nd device!")                
                time.sleep(5)
            if dongle_output2.decode().__contains__("\r\nDISCONNECTED."):
                connected2 = "0"
                print("Disconnected!")
                trying_to_connect2 = False
            dongle_output2 = " "
    while connected == "1" and connected2 =="1":        
        dongle_output3 = console.read(console.in_waiting)
        delay=10
        close_time=time.time()+delay
        i=0
        while True:
            myConIndex =  ('0000' if i%2 == 0 else '0001')
            console.write(str.encode("AT+TARGETCONN="))
            console.write(str.encode(myConIndex))
            console.write("\r".encode())
            console.write(str.encode("AT+SPSSEND="))
            console.write(str.encode(id_generator()+'-'+myConIndex))
            console.write("\r".encode())
            time.sleep(0.2)
            i+=1
            if time.time()>close_time:
                break
        console.write(str.encode("AT+SPSSEND=[DONE]\r"))
        time.sleep(0.2)
        print("Sending complete!\r\n")
        print("Exiting script...")
        exit()

This script will be used for the central BleuIO dongle. We need to find the port number of each dongle and the peripheral mac address.

Step 2:

Connect three BleuIO dongles on your PC. You can do the process on three different PC or Raspberry Pi.

I have connected both the central and the peripheral to one PC for this project.

After connecting the dongles, open device manager (windows) to find ports of each dongle.

On my PC, I have the BleuIO dongles connected on ports 7,8 and 18.

Let’s make COM7 the central , COM8 and COM18 as peripheral.

Now open the scripts and set the ports number on line 12. 

We also need to know the peripheral dongles mac address. 

To do that, we can simply advertise the dongle using AT+ADVSTART command .

  • Go to https://bleuio.com/web_terminal.html
  • Click on connect to BleuIO dongle
  • Select your port for peripheral
  • Type AT+ADVSTART

Do the same process for the other peripheral dongle.

Now both the peripheral dongle is advertising. We can do a gap scan from central to find their mac address. 

  • Go to https://bleuio.com/web_terminal.html
  • Click on connect to BleuIO dongle
  • Select your port for central
  • Type AT+DUAL (This will put the dongle in dual role)
  • Type AT+GAPSCAN

Now look for the dongle called BleuIO.

Update the script with the peripheral mac address (line 6,9)

Step 3 :

Now lets run the script.

Go to the script folder and type python py_serial_transfer.py

It will connect to both the peripheral dongles and send data randomly. 

You will see the responses on the web terminal screen. 

Please follow the video to get better understanding.

Share this post on :

C# desktop application to connect to BLE devices using BleuIO

Bluetooth Low Energy (BLE) is a low power wireless technology used for connecting devices with each other. It is a popular communication method especially in the era of Internet of Things. Several devices around the house have a build-in buetooth transceiver and most of them provide really useful capabilitites to automate jobs. For that reason it is really interesting to create desktop application using C# that connects to the devices around the house and manage them.

In this example we are going to create a simple C# windows form application to communicate with BleuIO using SerialPort. This script can be used to create Bluetooth Low Energy application using C# with BleuIO.

Let’s start

As a first step lets create a new project in visual studio and select C# windows form application from the list.

Choose a suitable name for your project.

Once the project is created, we will see a blank form screen where we will add buttons and labels to communicate with BleuIO graphically.

We will have buttons that connects and disconnects from BleuIO. An input field that takes AT commands from the user and sends it to BleuIO using SerialPort. And a text area will display the response from BleuIO to the screen.

The form will look like this

The .cs file associated to this will have the following code.

Source code is available at https://github.com/smart-sensor-devices-ab/bluetooth_low_energy_csharp_WFA.git

using System;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    
    public partial class Form1 : Form
    {
        SerialPort mySerialPort = new SerialPort("COM18", 57600, Parity.None, 8, StopBits.One);
        public Form1()
        {
            InitializeComponent();            
            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
            mySerialPort.Open();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            
            lbl_test.Text = "Connected";
        }
        
        //print response from the dongle
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string s = sp.ReadExisting();
            output_data.Invoke(new EventHandler(delegate { output_data.Text +=  s + "\r\n"; })); 

            //lbl_output.Invoke(this.myDelegate, new Object[] { s });
        }


        private void tb_cmd_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void submit_cmd_Click(object sender, EventArgs e)
        {
            output_data.Text = "";
            byte[] bytes = Encoding.UTF8.GetBytes(tb_cmd.Text);
            var inputByte = new byte[] { 13 };
            bytes = bytes.Concat(inputByte).ToArray();
            mySerialPort.Write(bytes, 0, bytes.Length);           
        }

        private void btn_disconnect_Click(object sender, EventArgs e)
        {
            mySerialPort.Close();
            Environment.Exit(0);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            byte[] bytes = Encoding.UTF8.GetBytes("\u0003");
            var inputByte = new byte[] { 13 };
            bytes = bytes.Concat(inputByte).ToArray();
            mySerialPort.Write(bytes, 0, bytes.Length);
        }

        private void output_data_TextChanged(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }
    }
}

As you can notice I wrote COM18 to connect to serial port because BleuIO device on my computer is connected to COM18.

You can check your COM port from device manager.

Lets run the project and click on connect button.

Once we are connected to BleuIO, we will be able to write AT commands using the input filed.

List of AT commands are available at https://www.bleuio.com/getting_started/docs/commands/

There is a stop button that write control+c to dongle and cancels current execution.

Here is a demo of this sample app.

Share this post on :

Create Bleutooth Low Energy Application with C# and BleuIO

Bluetooth Low Energy (BLE) is a low power wireless technology used for connecting devices with each other. It is a popular communication method especially in the era of Internet of Things. Several devices around the house have a build-in buetooth transceiver and most of them provide really useful capabilitites to automate jobs. For that reason it is really interesting to be able to create a main-device (like a PC) which will have an application that connects to the devices around the house and manage them.

In this example we are going to create a simple C# console application to communicate with BleuIO using SerialPort. This script can be used to create Bluetooth Low Energy application using C# with BleuIO.

Let’s start

As a first step lets create a new project in visual studio and select C# console application from the list.

This image has an empty alt attribute; its file name is image-1024x172.png

Choose a suitable name for your project and paste the following code to Program.cs file.

The source code is available at github.

using System;
using System.IO.Ports;
using System.Text;

namespace SerialPortExample
{
    class SerialPortProgram
    {                
        static SerialPort _port;
        static void Main(string[] args)
        {
            string portName;
            portName = SetPortName();
            _port = new SerialPort(portName,57600, Parity.None, 8, StopBits.One);
            // Instatiate this class
            SerialPortProgram serialPortProgram = new SerialPortProgram();
        }

        private SerialPortProgram()
        {
            _port.DataReceived += new
              SerialDataReceivedEventHandler(port_DataReceived);
            OpenMyPort();
            Console.WriteLine("Type q to exit.");
            bool continueLoop = true;
            string inputCmd;

            while (continueLoop)
            {
                inputCmd = Console.ReadLine();

                if (inputCmd == "q")
                {
                    continueLoop = false;
                    break;
                }
                else
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(inputCmd);
                    var inputByte = new byte[] { 13 };
                    bytes = bytes.Concat(inputByte).ToArray();
                    _port.Write(bytes, 0, bytes.Length);
                }
            }
        }

        private void port_DataReceived(object sender,
          SerialDataReceivedEventArgs e)
        {           
            // Show all the incoming data in the port's buffer
            Console.WriteLine(_port.ReadExisting());
        }

        //Open selected COM port
        private static void OpenMyPort()
        {
            try
            {
                _port.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error opening my port: {0}", ex.Message);
                Environment.Exit(0);
            }
        }

        // Display Port values and prompt user to enter a port.
        public static string SetPortName()
        {
            string portName;

            Console.WriteLine("Available Ports:");
            foreach (string s in SerialPort.GetPortNames())
            {
                Console.WriteLine("   {0}", s);
            }

            Console.Write("Enter COM port value (ex: COM18): ");
            portName = Console.ReadLine();
            return portName;
        }

    }
}

For this script a BleuIO dongle connected to the computer.

When we run the application, it suggests all the available ports on the computer and asks to write the com port number where the BleuIO is connected.

Once we write the correct port number, it starts communicating with BleuIO via SerialPort.

The response of AT commands from the BleuIO will be shown on the screen.

Find the list of available AT commands at BleuIO getting started guide.

The application will terminate with control+c or type ‘q’.

Share this post on :

How To Make a BLE enabled Smart Bulb with STM32

Home automation involves automating household environment equipment. To achieve that, we have created a smart bulb that is easy to install, and the attached equipment can be controlled over a web browser or smartphone app. The aim of this project is to control different home appliances using a web browser or smartphone.

1. Introduction

The project is showcasing a simple way of using the the BleuIO Dongle to turn on and off a light bulb that is connected to the STM32 Nucleo-144 via a 5V Relay.

You will need two dongles, one connected to the Nucleo board and one connected to a computer, running the web script.
When the BleuIO Dongle is connected to the Nucleo boards USB port the STM32 will recognize it and directly start advertising. This allows the other Dongle to connect to it.

It will also accept 3 different inputs from the UART:

inputresult
0Send ATI (Request device information) command to BlueIO Dongle.
1Manually turn the light bulb on
2Manually turn the light bulb off

We have used a STM32 Nucleo-144 development board with STM32H743ZI MCU (STM32H743ZI micro mbed-Enabled Development Nucleo-144 series ARM® Cortex®-M7 MCU 32-Bit Embedded Evaluation Board) for this example.

If you want to use another setup you will have to make sure it support USB Host and beware that the GPIO setup might be different and may need to be reconfigured in the .ioc file.

WARNING – THIS PROJECT INVOLVES HIGH VOLTAGES THAT CAN CAUSE SERIOUS INJURY OR DEATH. PLEASE TAKE ALL NECESSARY PRECAUTIONS, AND TURN OFF ALL POWER TO A CIRCUIT BEFORE WORKING ON IT.

2. Connecting the relay

Beware:

Always be very careful when experimenting with AC, electrical shock can result in serious injuries! NOTICE OF RISK; DISCLAIMER OF LIABILITY

alt text

Pinout and Connection to STM32 For the DC part of the Relay circuit connect S (signal) to pin PE4 on the STM32 NUCLEO board, also connect the Power supply (+) and ground (-) to +5V and GND respectively.

alt text

3. About the Code

You can get project HERE
https://github.com/smart-sensor-devices-ab/stm32_bleuio_lightbulb_example

This project based on our previous STM32 project (https://github.com/smart-sensor-devices-ab/stm32_bleuio_example) with these changes in the .ioc file:

In the pinout view we set the GPIO PE4 to OUTPUT and labeled it to ‘lightbulb’.alt text


In the USBH_CDC_ReceiveCallback function in USB_HOST\usb_host.c we copy the CDC_RX_Buffer into a external variable called dongle_response that is accessable from the main.c file.

void USBH_CDC_ReceiveCallback(USBH_HandleTypeDef *phost)
{
    if(phost == &hUsbHostFS)
    {
        // Handles the data recived from the USB CDC host, here just printing it out to UART
        rx_size = USBH_CDC_GetLastReceivedDataSize(phost);
        HAL_UART_Transmit(&huart3, CDC_RX_Buffer, rx_size, HAL_MAX_DELAY);

        // Copy buffer to external dongle_response buffer
        strcpy((char *)dongle_response, (char *)CDC_RX_Buffer);

        memset(CDC_RX_Buffer,0,RX_BUFF_SIZE);
        USBH_CDC_Receive(phost, CDC_RX_Buffer, RX_BUFF_SIZE);
    }

    return;
}


In main.c we create a simple intepreter so we can react to the data we are recieving from the dongle.

/**
  * @brief Simple dongle interpreter
  * @retval None
  */
void dongle_interpreter(uint8_t * input)
{

    if(strlen((char *)input) != 0)
    {
        if(strstr((char *)input, "\r\nADVERTISING...") != NULL)
        {
            isAdvertising = true;
        }
        if(strstr((char *)input, "\r\nADVERTISING STOPPED.") != NULL)
        {
            isAdvertising = false;
        }
        if(strstr((char *)input, "\r\nCONNECTED") != NULL)
        {
            isConnected = true;
            HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1, GPIO_PIN_SET);
        }
        if(strstr((char *)input, "\r\nDISCONNECTED") != NULL)
        {
            isConnected = false;
            HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1, GPIO_PIN_RESET);
        }
        if(strstr((char *)input, "L=0") != NULL)
        {
            isLightBulbOn = false;
            HAL_GPIO_WritePin(Lightbulb_GPIO_Port, Lightbulb_Pin, GPIO_PIN_RESET);

            writeToDongle((uint8_t*)DONGLE_SEND_LIGHT_OFF);

            uart_buf_len = sprintf(uart_tx_buf, "\r\nLight bulb is %s\r\n", isLightBulbOn ? "on":"off");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
        }
        if(strstr((char *)input, "L=1") != NULL)
        {
            isLightBulbOn = true;
            HAL_GPIO_WritePin(Lightbulb_GPIO_Port, Lightbulb_Pin, GPIO_PIN_SET);

            writeToDongle((uint8_t*)DONGLE_SEND_LIGHT_ON);

            uart_buf_len = sprintf(uart_tx_buf, "\r\nLight bulb is %s\r\n", isLightBulbOn ? "on":"off");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
        }
    }
    memset(&dongle_response, 0, RSP_SIZE);
}


We also update the handleUartInput function so we can have manual control over the light bulb via the UART.

/**
  * @brief Simple uart input handler
  * @retval None
  */
void handleUartInput(UARTCommandTypeDef cmd)
{
    switch(cmd)
    {
        case UART_RX_0:
        {
            // 0
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(0 pressed)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            if(isBleuIOReady)
            {
                writeToDongle((uint8_t*)DONGLE_CMD_ATI);
            } else
            {
                uart_buf_len = sprintf(uart_tx_buf, BLEUIO_NOT_READY_MSG);
                HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            }
            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_1:
        {
            // 1
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(1 pressed light bulb on!)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            HAL_GPIO_WritePin(Lightbulb_GPIO_Port, Lightbulb_Pin, GPIO_PIN_SET);
            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_2:
        {
            // 2
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(2 pressed light bulb off!)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            HAL_GPIO_WritePin(Lightbulb_GPIO_Port, Lightbulb_Pin, GPIO_PIN_RESET);

            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_NONE:
        {
            break;
        }
        default:
        {
            uartStatus = UART_RX_NONE;
            break;
        }
    }
}

We put the intepreter function inside the main loop.

/* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    MX_USB_HOST_Process();

    /* USER CODE BEGIN 3 */
    // Simple handler for uart input
    handleUartInput(uartStatus);
    // Inteprets the dongle data
    dongle_interpreter(dongle_response);

    // Starts advertising as soon as the Dongle is ready.
    if(!isAdvertising && !isConnected && isBleuIOReady)
    {
        HAL_Delay(200);
        writeToDongle((uint8_t*)DONGLE_CMD_AT_ADVSTART);
        isAdvertising = true;
    }
  }
  /* USER CODE END 3 */

4. Using the example project

4.1 What you will need

5. How to setup project

5.1 Downloading the project from GitHub

Get project HERE
https://github.com/smart-sensor-devices-ab/stm32_bleuio_lightbulb_example

Either clone the project, or download it as a zip file and unzip it, into your STM32CubeIDE workspace.

5.2 Importing as an Existing Project

  • From STM32CubeIDE choose File>Import…
    alt text
  • Then choose General>Existing Projects into Workspace then click ‘Next >’
    alt text
  • Make sure you’ve choosen your workspace in ‘Select root directory:’
  • You should see the project “stm32_bleuio_example”, check it and click ‘Finish’.
    alt text

6. Running the example

  • In STMCubeIDE click the hammer icon to build the project.
  • Open up the ‘STMicroelectronics STLink Viritual COM Port’ with a serial terminal emulation program like TeraTerm, Putty or CoolTerm.Serial port Setup:
    Baudrate: 115200
    Data Bits: 8
    Parity: None
    Stop Bits: 1
    Flow Control: None
  • Connect the BleuIO Dongle before running the example .
  • In STMCubeIDE click the green play button to flash and run it on your board. The first time you click it the ‘Run Configuration’ window will appear. You can just leave it as is and click run.
  • You should be greeted by this welcome message:Welcome!
  • Wait until the message: “[BleuIO Dongle Ready]” is shown.

    Welcome!
  • You can now connect with the other dongle using the script.

You can also use the uart commands (0, 1 or 2):

  • Press 0 to get device information.

    1 to turn on lightbulb.

    2 to turn off lightbulb.


    Dongle response will be printed to UART.

7. Controlling the light from a web browser

We wrote a simple script that connects to the dongle and sends signals to toggle the light from the web browser.

For this script to work, we need

Steps

Create a simple Html file called index.html which will serve as the frontend of the script. This Html file contains some buttons that help connect and signal to the remote dongle, which is connected to stm32.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <title>Control Light using Bleutooth Low Energy</title>
  </head>
  <body class="mt-5">
    <div class="container mt-5">
      <h1 class="mb-5">Control Light using Bleutooth Low Energy</h1>
      <button class="btn btn-success" id="connect">Connect</button>
      <button class="btn btn-warning" id="lightOn" disabled>Turn On</button>
      <button class="btn btn-danger" id="lightOf" disabled>Turn Off</button>
    </div>
    <div class="container mt-5">
      <img id="light" src="light_off.png" alt="" />
    </div>

    <script src="script.js"></script>
  </body>
</html>

Create a js file called script.js and include it at the bottom of the Html file. This js file uses the BleuIO js library to write AT commands and communicate with the other dongle.

import * as my_dongle from "bleuio";
const dongleToConnect = "[0]40:48:FD:E5:35:A5";
import lightOnImg from "./light_on.png";
import lightOfImg from "./light_off.png";
document.getElementById("connect").addEventListener("click", function () {
  my_dongle.at_connect();
  document.getElementById("lightOn").disabled = false;
  document.getElementById("lightOf").disabled = false;
  document.getElementById("connect").disabled = true;
});

document.getElementById("lightOn").addEventListener("click", function () {
  my_dongle
    .ati()
    .then((data) => {
      //make central if not
      if (JSON.stringify(data).includes("Peripheral")) {
        console.log("peripheral");
        my_dongle.at_central().then((x) => {
          console.log("central now");
        });
      }
    })
    .then(() => {
      // connect to dongle
      my_dongle
        .at_getconn()
        .then((y) => {
          if (JSON.stringify(y).includes(dongleToConnect)) {
            console.log("already connected");
          } else {
            my_dongle.at_gapconnect(dongleToConnect).then(() => {
              console.log("connected successfully");
            });
          }
        })
        .then(() => {
          // send command to control light
          my_dongle.at_spssend("L=1").then(() => {
            console.log("Turned on");
            document.getElementById("light").src = lightOnImg;
          });
        });
    });
});

document.getElementById("lightOf").addEventListener("click", function () {
  my_dongle
    .ati()
    .then((data) => {
      //make central if not
      if (JSON.stringify(data).includes("Peripheral")) {
        console.log("peripheral");
        my_dongle.at_central().then((x) => {
          console.log("central now");
        });
      }
    })
    .then(() => {
      // connect to dongle
      my_dongle
        .at_getconn()
        .then((y) => {
          if (JSON.stringify(y).includes(dongleToConnect)) {
            console.log("already connected");
          } else {
            my_dongle.at_gapconnect(dongleToConnect).then(() => {
              console.log("connected successfully");
            });
          }
        })
        .then(() => {
          // send command to control light
          my_dongle.at_spssend("L=0").then(() => {
            console.log("Turned off");
            document.getElementById("light").src = lightOfImg;
          });
        });
    });
});

The script js file has three button actions; connect and control light.

Now we need to know the ID of the other dongle connected to STM32 so that we can connect to it. You can use this web terminal to get the dongle ID.

- Open this site https://bleuio.com/web_terminal.html and click connect to dongle.
- Select the appropriate port to connect.
- Once it says connected, type **"ATI"**. This will show dongle information and current status.
- If the dongle is on peripheral role, set it to central by typing **"AT+CENTRAL"**
- Now do a gap scan by typing **"AT+GAPSCAN"**
- Once you see your dongle on the list ,stop the scan by pressing control+c
- Copy the ID and paste it into the script (script.js) line #2
alt text

You will need a web bundler. You can use parcel.js

Once parcel js installed, go to the root directory and type “parcel index.html”. This will start your development environment.

alt text

Open the script on a browser using parcel js.

You can easily connect to the dongle and turn on-off light from there.

alt text

You can also access the script athttps://smart-sensor-devices-ab.github.io/stm32_bleuio_lightbulb_example/web%20script/dist/index.html

Share this post on :

Bluetooth Low Energy (BLE) Tutorial for Beaglebone using BleuIO

1. Introduction

This is a simple example showcasing how to control a BleuIO dongle connected to Beaglebone Black using a python script.

When running the script, it will first ask for the com port where the dongle is connected (usually ‘/dev/ttyACM0’). After that, the BleuIO will start advertising. Every 8th second it will turn on one of the onboard Beaglebone Black LEDs whilst changing the BLE advertising name to indicate which LED is on.

We are using the Linux debian image: ‘OMAP3/DM3730 Debian 9.5 2018-10-07 4GB SD LXQT’ (https://beagleboard.org/latest-images).

alt text

2. About the Code

You can get access to the project HERE
https://github.com/smart-sensor-devices-ab/beaglebone_bleuio_example

We are using the Adafruit_BBIO python library that comes with the Beaglebone to control the onboard LEDs. First we define the LEDs names and then set them as GPIO Outputs. Then we define the advertising messages that the BleuIO will switch between. Lets break one down:

“10:09:42:6C:65:75:49:4F:20:4C:45:44:20:30:20:4F:4E:”

“10” is the size of the advertising packet in HEX.
“09” is the flag for device name (Complete Local Name).
“42:6C:65:75:49:4F:20:4C:45:44:20:30:20:4F:4E” is the packet itself, translated from HEX to ASCII it says: “BleuIO LED 0 ON”

Afterwards the user is presented with a message to input the com port the BleuIO is connected to. If you are not using a USB Hub the port should be ‘/dev/ttyACM0’.

You can change the comport name in the Python script and fill in your COM port.

com_input = "/dev/ttyACM0"

The script continues into the main loop, where it will first make sure all LEDs are off and then start BLE advertising.

The loop iterates through all four LEDs. In every iteration it turns one LED on and advertise the LED name then continue to the next LED. This will continue until the script is aborted.

import serial
import time
import Adafruit_BBIO.GPIO as GPIO


LED_USR0 = "USR0"
LED_USR1 = "USR1"
LED_USR2 = "USR2"
LED_USR3 = "USR3"

GPIO.setup(LED_USR0, GPIO.OUT)
GPIO.setup(LED_USR1, GPIO.OUT)
GPIO.setup(LED_USR2, GPIO.OUT)
GPIO.setup(LED_USR3, GPIO.OUT)

LED0_ON_ADV_MSG = "10:09:42:6C:65:75:49:4F:20:4C:45:44:20:30:20:4F:4E:"
LED1_ON_ADV_MSG = "10:09:42:6C:65:75:49:4F:20:4C:45:44:20:31:20:4F:4E:"
LED2_ON_ADV_MSG = "10:09:42:6C:65:75:49:4F:20:4C:45:44:20:32:20:4F:4E:"
LED3_ON_ADV_MSG = "10:09:42:6C:65:75:49:4F:20:4C:45:44:20:33:20:4F:4E:"

# Turn off all LEDs
GPIO.output(LED_USR0, GPIO.LOW)
time.sleep(0.1)
GPIO.output(LED_USR1, GPIO.LOW)
time.sleep(0.1)
GPIO.output(LED_USR2, GPIO.LOW)
time.sleep(0.1)
GPIO.output(LED_USR3, GPIO.LOW)
time.sleep(0.1)

print("\nBlueIO BeagleBone Example!\n\n")
connecting_to_dongle = 0
com_input = ""

start_input = 0
valid_input = 0
while start_input == 0:
    com_input = input(
        "Enter Com port of Dongle (default for BeagleBone: '/dev/ttyACM0'):\n>>"
    )
    print("\nComport to use: " + com_input)
    input_continue = input(
        "If your happy with your choice just press Enter to continue the script. Else type E to exit or R to redo your choice. \n>>"
    )
    if input_continue.upper() == "E":
        start_input = 1
    elif input_continue.upper() == "":
        start_input = 1
    elif input_continue.upper() == "R":
        valid_input = 0
        start_input = 0
if input_continue.upper() == "E":
    print("Exiting script...")
    exit()

console = None

while 1:
    try:
        print("Please wait...")
        time.sleep(0.5)
        console.write(str.encode("AT+DUAL"))
        console.write("\r".encode())
        time.sleep(0.5)
        print("Starting Advertising...")
        console.write(str.encode("AT+ADVSTART"))
        console.write("\r".encode())
        time.sleep(0.5)
        led_turn = 0
        # Turn off all LEDs
        GPIO.output(LED_USR0, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR1, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR2, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR3, GPIO.LOW)
        time.sleep(0.1)
        while True:
            if led_turn == 0:
                print("\nTurning LED USR0 ON")
                console.write(str.encode("AT+ADVRESP="))
                console.write(LED0_ON_ADV_MSG.encode())
                console.write("\r".encode())
                GPIO.output(LED_USR0, GPIO.HIGH)
                GPIO.output(LED_USR1, GPIO.LOW)
                GPIO.output(LED_USR2, GPIO.LOW)
                GPIO.output(LED_USR3, GPIO.LOW)
                led_turn = led_turn + 1
            elif led_turn == 1:
                print("\nTurning LED USR1 ON")
                console.write(str.encode("AT+ADVRESP="))
                console.write(LED1_ON_ADV_MSG.encode())
                console.write("\r".encode())
                GPIO.output(LED_USR0, GPIO.LOW)
                GPIO.output(LED_USR1, GPIO.HIGH)
                GPIO.output(LED_USR2, GPIO.LOW)
                GPIO.output(LED_USR3, GPIO.LOW)
                led_turn = led_turn + 1
            elif led_turn == 2:
                print("\nTurning LED USR2 ON")
                console.write(str.encode("AT+ADVRESP="))
                console.write(LED2_ON_ADV_MSG.encode())
                console.write("\r".encode())
                GPIO.output(LED_USR0, GPIO.LOW)
                GPIO.output(LED_USR1, GPIO.LOW)
                GPIO.output(LED_USR2, GPIO.HIGH)
                GPIO.output(LED_USR3, GPIO.LOW)
                led_turn = led_turn + 1
            elif led_turn == 3:
                print("\nTurning LED USR3 ON")
                console.write(str.encode("AT+ADVRESP="))
                console.write(LED3_ON_ADV_MSG.encode())
                console.write("\r".encode())
                GPIO.output(LED_USR0, GPIO.LOW)
                GPIO.output(LED_USR1, GPIO.LOW)
                GPIO.output(LED_USR2, GPIO.LOW)
                GPIO.output(LED_USR3, GPIO.HIGH)
                led_turn = 0

            time.sleep(8)

    except KeyboardInterrupt:
        GPIO.output(LED_USR0, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR1, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR2, GPIO.LOW)
        time.sleep(0.1)
        GPIO.output(LED_USR3, GPIO.LOW)
        time.sleep(0.1)
        print("Exiting script...")
        exit()
    except:
        print("\n\nDongle not connected.\n")
        connecting_to_dongle = 0
        while connecting_to_dongle == 0:
            try:
                print("Trying to connect to dongle...")
                console = serial.Serial(
                    port=com_input,
                    baudrate=57600,
                    parity="N",
                    stopbits=1,
                    bytesize=8,
                    timeout=0,
                )
                if console.is_open.__bool__():
                    connecting_to_dongle = 1
                    print("\n\nConnected to Dongle in port: " + com_input + ".\n")
            except:
                print(
                    "Dongle not found. Retrying connection to port: "
                    + com_input
                    + "..."
                )
                time.sleep(5)

3. Using the example project

3.1 What you will need

4. How to setup project

4.1 Downloading the project from GitHub

Get access to the project HERE
https://github.com/smart-sensor-devices-ab/beaglebone_bleuio_example

Either clone the project, or download it as a zip file and unzip it, into a folder on your BeagleBone.

You can also create a new python file using the Cloud9 IDE from the BeagleBone (run by going to http://192.168.7.2:3000/).
alt text

Copy the code and pasting it into the newly created file.

alt text

4.2 Installing pyserial

To run the script you will need to install the python library pyserial.

The easiest way of doing this is just connecting to the BeagleBone via shh (the default password is temppwd):
alt text

or using the bash tab in the Cloud9 IDE and type:

 sudo pip3 install pyserial
alt text

5. Running the example

Go to the folder where you have the python script file and run:
(Pyserial needs sudo-privileges to function.)

sudo python3 name_of_script.py
Share this post on :

Bluetooth Low Energy (BLE) Tutorial for Arduino using BleuIO

1. Introduction

The project is a simple example showcasing a quick way to setup an Arduino with a USB Host Shield as a USB CDC Host capable of communicating with the BleuIO Dongle.

When a BleuIO Dongle is connected to the USB port, the BleuIO Dongle will start advertising. It will then act as a terminal, taking input and sending data to the Arduino Virtual Com Port.

We have used an Arduino Uno Rev. 3 with SparkFun’s USB Host Shield (DEV-09947) for this example.

2. About the Code

You can get project HERE
https://github.com/smart-sensor-devices-ab/arduino_bleuio_example
This project based on the ‘acm_terminal’ example in the Host USB Shield Library 2.0

alt text

The largest possible max.packet size for the function Acm.RcvData() is 64 bytes, so to accommodate the amount of data we will receive, we are using three buffers to receive the data from the BleuIO Dongle.

If the buffers have received any data, we print it out to the serial terminal connected to the Virtual COM Port.

void loop()
{
    Usb.Task();

    if( Acm.isReady()) {
       uint8_t rcode;
       uint8_t rcode2;
       uint8_t rcode3;

       /* reading the keyboard */
       if(Serial.available()) {
         uint8_t data= Serial.read();
         /* sending to the BleuIO Dongle */
         rcode = Acm.SndData(1, &data);
         if (rcode)
            ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
       }//if(Serial.available()...

        if(start_flag == 0x00)
        {
            rcode = Acm.SndData(strlen((char *)START_CMDS), (uint8_t *)START_CMDS);
            if (rcode)
            {
                ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
            }

          start_flag = 0x01;
        }
        /* reading the BleuIO Dongle */
        uint8_t  buf[64];
        uint16_t rcvd = 64;
        uint8_t  buf2[64];
        uint16_t rcvd2 = 64;
        uint8_t  buf3[64];
        uint16_t rcvd3 = 64;
        uint8_t  dongle_input[3*64];
        uint16_t input_indx = 0;

        memset(dongle_input, 0, sizeof(dongle_input));

        rcode = Acm.RcvData(&rcvd, buf);
        delay(1);
        rcode2 = Acm.RcvData(&rcvd2, buf2);
        delay(1);
        rcode3 = Acm.RcvData(&rcvd3, buf3);
         if (rcode && rcode != hrNAK)
         {
            ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
         }

         if (rcode2 && rcode2 != hrNAK)
         {
             ErrorMessage<uint8_t>(PSTR("Ret"), rcode2);
         }

         if (rcode3 && rcode3 != hrNAK)
         {
             ErrorMessage<uint8_t>(PSTR("Ret"), rcode3);
         }


            if( rcvd ) { //more than zero bytes received
              for(uint16_t i=0; i < rcvd; i++ ) {
                Serial.print((char)buf[i]); //printing on the screen
                dongle_input[input_indx] = buf[i];
                input_indx++;
              }
            }

            if( rcvd2 ) { //more than zero bytes received
              for(uint16_t i=0; i < rcvd2; i++ ) {
                Serial.print((char)buf2[i]); //printing on the screen
                dongle_input[input_indx] = buf2[i];
                input_indx++;
              }
            }

            if( rcvd3 ) { //more than zero bytes received
              for(uint16_t i=0; i < rcvd3; i++ ) {
                Serial.print((char)buf3[i]); //printing on the screen
                dongle_input[input_indx] = buf3[i];
                input_indx++;
              }
            }
            dongle_input[input_indx] = 0x00;

            // Example on a way for the Arduino to react to BleuIO events
            if(strlen((char *)dongle_input) != 0)
            {
              if(strstr((char *)dongle_input, "handle_evt_gap_connected") != NULL)
              {
                Serial.print("<<CONNECTION DETECTED!>>");
              }
              else if(strstr((char *)dongle_input, "handle_evt_gap_disconnected") != NULL)
              {
                Serial.print("<<CONNECTION LOST!>>");
              }
            }
    }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING..
}

We also store the latest data from the dongle into the dongle_input buffer and run it through a simple “parser” to showcase an easy way of how you can react to events and have the Arduino do something.

In this example, we are explicitly looking for BLE connection or disconnect events. When found, we just print out “<<CONNECTION DETECTED!>>” or “<<CONNECTION LOST!>>” to the terminal.

3. Using the example project

3.1 What you will need

3.2 Requirments for the SparkFun board

  • With the SparkFun board, it seems like you MUST supply external power on Vin or the barrel jack. 5V from the USB cable did not work.
  • You must also apply a jumper from pin D7 to RESET.

4. How to setup project

4.1 Downloading the project from GitHub

Get project HERE
https://github.com/smart-sensor-devices-ab/arduino_bleuio_example

Either clone the project, or download it as a zip file and unzip it, into your Arduino folder.

4.2 Downloading the USB Host Shield Library 2.0

Either download the Library from Here (https://felis.github.io/USB_Host_Shield_2.0/) and place the folder into your libraries folder inside your Arduino folder. (For information on installing libraries, see: http://www.arduino.cc/en/Guide/Libraries)

Or download it through the Arduino IDE:

  • In Arduino IDE choose Sketch>Include Library>Manage Library

    alt text
  • Search for USB Host Shield Library 2.0 and click ‘Install’

    alt text

5. Running the example

  • In Arduino IDE click the upload button to upload the project to your Arduino.

    alt text
  • Open up the ‘Arduino Uno Viritual COM Port’ with a serial terminal emulation program like TeraTerm, Putty or CoolTerm.Serial port Setup:
    Baudrate: 115200
    Data Bits: 8
    Parity: None
    Stop Bits: 1
    Flow Control: None
  • Or inside the Arduino IDE open up Arduino Monitor and in the bottom right corner select ‘Carriage Return’ and ‘115200 baud’
    alt text
  • You should see the word ‘Start’ and then see the dongle running two commands: setting response data and starting the advertising. You can now type commands to the dongle.

    alt text
Share this post on :

Create BLE project with STM32 and BleuIO

1. Introduction

The project is a simple example showcasing a quick way to set up a STM32Cube project as a USB CDC Host capable of communicating with the BleuIO Dongle.

When a BleuIO Dongle is connected to the Nucleo boards USB port the STM32 will recognize it. It will then accept 3 different inputs from the UART and send one of 3 preprogrammed commands to the BleuIO Dongle based on the input. The commands that are used in this example are:

  • ATI (Dongle Information)
  • AT+ADVSTART (Starts Advertising)
  • AT+ADVSTOP (Stops Advertising)

We have used a STM32 Nucleo-144 development board with STM32H743ZI MCU (STM32H743ZI micro mbed-Enabled Development Nucleo-144 series ARM® Cortex®-M7 MCU 32-Bit Embedded Evaluation Board) for this example.

If you want to use another setup you will have to make sure it support USB Host and beware that the GPIO setup might be different and may need to be reconfigured in the .ioc file.

2. About the Code

You can get project HERE
https://github.com/smart-sensor-devices-ab/stm32_bleuio_example

This project based on a new STM32 project with these changes in the .ioc file:

Under ‘Connectivity’ the ‘USB_OTG_FS’-mode is changed to Host_Only and in the NVIC Settings all global interrupts are enabled.

alt text

And under ‘Middleware’ the ‘USB_HOST’- ‘Class for FS IP’ is set to ‘Communication Host Class (Virtual Port Com)’.

alt text



To make sure the host would recognize when the bootloader is done and the BleuIO firmware is running this was added in the USBH_UserProcess function in ‘usb_host.c’ (found under ‘USB_HOST’ -> ‘App’ folder):

static void USBH_UserProcess  (USBH_HandleTypeDef *phost, uint8_t id)
{
  /* USER CODE BEGIN CALL_BACK_1 */
  switch(id)
  {
  case HOST_USER_SELECT_CONFIGURATION:
  break;

  case HOST_USER_DISCONNECTION:
  Appli_state = APPLICATION_DISCONNECT;
  isBleuIOReady = false;

  // Turn on Red LED, turn off Green and Yellow LED
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_SET);
  break;

  case HOST_USER_CLASS_ACTIVE:
  Appli_state = APPLICATION_READY;
  // Check if BleuIO firmware is running
  // (idProduct:0x6001 = bootloader, idProduct:0x6002 = bleuio fw)
  if(phost->device.DevDesc.idProduct == 0x6002)
  {
      isBleuIOReady = true;
      // Sends message to uart that BleuIO is connected and ready
      HAL_UART_Transmit(&huart3, (uint8_t*)BLEUIO_READY, strlen(BLEUIO_READY), HAL_MAX_DELAY);

      // Turn on Green LED, turn off Yellow and Red LED
      HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_SET);
      HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1, GPIO_PIN_RESET);
      HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_RESET);

      // Start receiving from usb
      USBH_CDC_Receive(&hUsbHostFS, CDC_RX_Buffer, RX_BUFF_SIZE);
  }
  break;

  case HOST_USER_CONNECTION:
  Appli_state = APPLICATION_START;
  isBleuIOReady = false;
  // Turn on Yellow LED, turn off Green and Red LED
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1, GPIO_PIN_SET);
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_RESET);
  break;

  default:
  break;
  }
  /* USER CODE END CALL_BACK_1 */
}

The Green, Red and Yellow LEDs on the Nucleo board is also setup to change based on the connection status.

Red = Disconnnected.
Yellow = Connecting.
Green = Connected.

An external variable bool isBleuIOReady is also set so the status of the dongle is accessible from main.c.

Once the BleuIO dongle is confirmed to be connected the USBH_CDC_Receive function is run to start reciving data from the USB CDC.

The USBH_CDC_ReceiveCallback also needs to be implemented:

void USBH_CDC_ReceiveCallback(USBH_HandleTypeDef *phost)
{
    if(phost == &hUsbHostFS)
    {
        // Handles the data recived from the USB CDC host, here just printing it out to UART
        rx_size = USBH_CDC_GetLastReceivedDataSize(phost);
        HAL_UART_Transmit(&huart3, CDC_RX_Buffer, rx_size, HAL_MAX_DELAY);

        // Reset buffer and restart the callback function to receive more data
        memset(CDC_RX_Buffer,0,RX_BUFF_SIZE);
        USBH_CDC_Receive(phost, CDC_RX_Buffer, RX_BUFF_SIZE);
    }

    return;
}

In this example the recieved data is just echoed to the UART.



To send data to the Dongle the USBH_CDC_Transmit function is used. In this example UART input is used to send different commands.

For this purpose a wrapper function has been created that can be accessed from main.c:

/**
  * @brief Simple function that takes a string and transmit it to the dongle
  * @retval None
  */
void writeToDongle(uint8_t * cmd)
{
    USBH_CDC_Transmit(&hUsbHostFS, cmd, strlen((char *)cmd));
}

In main.c HAL_UART_RxCpltCallback is implemented to recieve input from Uart and a simple UART input handler:

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
    if(UartHandle == &huart3)
    {
        RX_value = (int)aRxBuffer[0];
        uartStatus = UART_RX_NONE;

        switch(RX_value)
        {
            case UART_RX_0:
            {
                uartStatus = UART_RX_0;
                break;
            }
            case UART_RX_1:
            {
                uartStatus = UART_RX_1;
                break;
            }
            case UART_RX_2:
            {
                uartStatus = UART_RX_2;
                break;
            }
            default:
            {
                uartStatus = UART_RX_NONE;
                break;
            }
        }
        // Resets uart recieve interrupt mode
        HAL_UART_Receive_IT(&huart3, (uint8_t *)aRxBuffer, RXBUFFERSIZE);
    }
}


/**
  * @brief Simple uart input handler
  * @retval None
  */
void handleUartInput(UARTCommandTypeDef cmd)
{
    switch(cmd)
    {
        case UART_RX_0:
        {
            // 0
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(0 pressed)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            if(isBleuIOReady)
            {
                writeToDongle((uint8_t*)DONGLE_CMD_ATI);
            } else
            {
                uart_buf_len = sprintf(uart_tx_buf, BLEUIO_NOT_READY_MSG);
                HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            }
            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_1:
        {
            // 1
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(1 pressed)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            if(isBleuIOReady)
            {
                writeToDongle((uint8_t*)DONGLE_CMD_AT_ADVSTART);
            } else
            {
                uart_buf_len = sprintf(uart_tx_buf, BLEUIO_NOT_READY_MSG);
                HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            }
            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_2:
        {
            // 2
            uart_buf_len = sprintf(uart_tx_buf, "\r\n(2 pressed)\r\n");
            HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            if(isBleuIOReady)
            {
                writeToDongle((uint8_t*)DONGLE_CMD_AT_ADVSTOP);
            } else
            {
                uart_buf_len = sprintf(uart_tx_buf, BLEUIO_NOT_READY_MSG);
                HAL_UART_Transmit(&huart3, (uint8_t *)uart_tx_buf, uart_buf_len, HAL_MAX_DELAY);
            }
            uartStatus = UART_RX_NONE;
            break;
        }
        case UART_RX_NONE:
        {
            break;
        }
        default:
        {
            uartStatus = UART_RX_NONE;
            break;
        }
    }
}

The handleUartInput() handles the inputs 0, 1 and 2 and maps each to a certain Dongle commands. The handler is then put inside the main loop.

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */
    MX_USB_HOST_Process();
    /* USER CODE BEGIN 3 */
    // Simple handler for uart input
    handleUartInput(uartStatus);
  }
  /* USER CODE END 3 */

3. Using the example project

3.1 What you will need

4. How to setup project

4.1 Downloading the project from GitHub

Get project HERE
https://github.com/smart-sensor-devices-ab/stm32_bleuio_example

Either clone the project, or download it as a zip file and unzip it, into your STM32CubeIDE workspace.

4.2 Importing as an Existing Project

  • From STM32CubeIDE choose File>Import…
    alt text
  • Then choose General>Existing Projects into Workspace then click ‘Next >’
    alt text
  • Make sure you’ve choosen your workspace in ‘Select root directory:’
  • You should see the project “stm32_bleuio_example”, check it and click ‘Finish’.
    alt text

5. Running the example

  • In STMCubeIDE click the hammer icon to build the project.
  • Open up the ‘STMicroelectronics STLink Virtual COM Port’ with a serial terminal emulation program like TeraTerm, Putty or CoolTerm.Serial port Setup:
    Baudrate: 115200
    Data Bits: 8
    Parity: None
    Stop Bits: 1
    Flow Control: None
  • In STMCubeIDE click the green play button to flash and run it on your board. The first time you click it the ‘Run Configuration’ window will appear. You can just leave it as is and click run.
  • Connect the BleuIO Dongle.
  • Wait until the message: “[BleuIO Dongle Ready]” is shown.
Welcome!

– Press 0 to get device information:

Welcome!

– Press 1 to start advertising:

Welcome!

– Press 2 to stop advertising:

Welcome!


BlueIO dongle responses will be printed out to Virtual COM Port.

Share this post on :