Saturday, August 10, 2024

Design Guide for Scalable Ultra-Low Power Weather Station Based on Bluetooth Low Energy Technology

 

Introduction
This blog post will detail a Bluetooth Low Energy-based system that serves as the foundation for a scalable centralized wireless system consisting of low-power nodes that gather environmental sensor data.

Traditionally, it has been impossible to design a low-power and scalable system that also allows bidirectional communication between end nodes and a central node using Bluetooth Low Energy (LE). However, this is now possible with the right hardware and by utilizing a relatively new Bluetooth feature called Periodic Advertising with Responses (PAwR).

In this project, we will be using Nordic Semiconductor's popular Bluetooth Low Energy platform (including SDK, hardware, tools, and more!). Specifically, we will be using a few nRF52840 development kits.

System Design and Operation

The example project we’ll design and build is a Bluetooth LE-based Weather Station.

For simplicity, we’ll use a single sensor (on each sensor node) that can read both temperature and humidity.

This can easily be expanded to include more sensors or a different sensor that can read other environmental parameters (e.g., barometric pressure, CO, CO2, gas, etc.).

Below is a diagram that shows the different components of the system:

As you can see, our system has three main types of components.

Let’s list each one and describe its role and behavior.

  • Sensor Collector:
    • The sensor collector will be very simple in terms of hardware components. It will consist of only an nRF52840 DK without peripherals or additional attached components.
    • This is the “central” node in the system (not to be confused with the Bluetooth LE central role).
    • Instead, this refers to the device acting like a gateway, access point, or hub, meaning the system will not operate without it. The system will be configured in a star topology setup (hub spoke model).
    • The sensor collector’s role is to collect data from all the sensors and expose the data to the user(s) via a smartphone interface.
    • It acts in three LE roles: the PAwR advertiser (receiving data and sending commands from/to the sensor nodes), LE Central (connecting to the sensor nodes), and LE Peripheral (exposing the sensor data to a smartphone app).
    • It will be mains-powered, so no power optimization is needed.
    • The sensor collector stores the last received values and exposes them via a GATT Server that can be read by a connected smartphone.
  • Sensor Nodes:
    • In terms of hardware, each sensor node will be made up of the following:
      • nRF52840 DK
      • e-Paper display
      • A temperature+humidity sensor (the Sensirion SHT40)
    • Sensor nodes will act in both LE PAwR synchronized and LE Peripheral roles.
    • PAwR allows the sensor nodes to report the sensor data to and receive commands from the sensor collector.
    • The LE Peripheral role allows the sensor collector to transfer the periodic advertising sync information to each sensor node (via the Periodic Advertising Sync Transfer procedure).
    • This process helps save power on the sensor nodes since they don’t have to go through the process of discovering the PA (Periodic Advertising) train. This might not seem significant, but over time, if the devices repeatedly lose sync and need to re-sync, then power consumption from the PA train discovery process adds up.
    • This device will be battery-powered, so we have to optimize its operation for power consumption.
    • The e-paper display will be used to report three pieces of information:
      • Device ID
      • Temperature reading
      • Humidity reading
      • A sensor node will periodically read both temperature and humidity.
      • It will also print those to the local e-paper display.
    • A Sensor Node will receive commands from the sensor collector.
    • A command will indicate whether it wants to read the temperature or humidity reading.
    • The command will apply to all synchronized Sensor Nodes, and they will all report these values back to the sensor collector.
    • Each Sensor Node will be assigned an ID at compile-time
    • The ID will be included in the advertising data and the responses that are sent back to the sensor collector for identification purposes.
  • Smartphone:
    • To mimic a real-world application, we will design the sensor collector to implement an LE Peripheral.
    • This will allow the sensor collector to report the temperature and humidity measurements coming from all the sensor nodes in the system in a unified manner.
    • A connected smartphone can read each sensor node’s latest data, including temperature and humidity measurements.
    • A connected smartphone can subscribe to notifications of temperature and humidity readings from each sensor node and will know exactly which sensor node the readings come from.
    • We’ll use the Nordic nRF Connect for Mobile application to interface (as an LE Central) with the sensor collector.
    • It is recommended to use an Android phone for this purpose due to some necessary features not being available in the iOS version of the nRF Connect for Mobile app.

For the purposes of the project implementation in the course, we will be using only three sensor nodes. However, the system design allows us to scale it to potentially thousands of sensor nodes without having to change much in the architecture. This is the power of PAwR!

Hardware Components

In terms of hardware components, here’s a complete list of what you’ll need to build the whole project:

QuantityHardware Component
4Nordic Semiconductor nRF52840 DK
1Nordic Semiconductor Power Profiler Kit II
3Waveshare 250×122, 2.13inch E-Ink raw display panel
3Waveshare Universal E-Paper Raw Panel Driver Shield (B)
3Adafruit Sensirion SHT40 Temperature & Humidity Sensor
3STEMMA QT / Qwiic JST SH 4-pin to Premium Male Headers Cable
Alternative Link (in case out of stock)
1Glarks 240Pcs 2.54mm Straight Single Row PCB Board Female Pin Header Kit
1Soldering Iron Kit

Software Components

Here’s a list of the various software components used in the project:

We also have all the source code hosted in a GitHub repo to accompany the course. You can find the repo here.

Power Consumption Optimization

Achieving low power consumption is crucial for the sensor nodes in our system, especially since they will be running on batteries.

For this purpose, we dedicate a full lesson to optimizing power consumption on the sensor node devices in the course. For this, we employ a few strategies:

  • We will use Nordic Semiconductor’s Power Profiler Kit II (PPK2) to measure our application’s current draw and electric charge consumption.
  • This is used alongside nRF Connect for Desktop (and specifically the Power Profiler application included within it).
  • After the measurement process, we prioritize the device operations based on electric charge consumption (the higher the consumption, the higher the priority).
  • We employ a few strategies to optimize power consumption, including turning off peripherals, adjusting how often operations occur, and adjusting the PAwR timing parameters.

Video Demo

Course Prerequisites

My Honest Thoughts On The nRF Connect SDK

Even though this is a sponsored course and blog post, you may already know that I’ve been working with Nordic Semiconductor’s solutions and ecosystem long before they sponsored any of my work.

So, I wanted to weigh in with my honest personal opinion on the whole nRF Connect SDK ecosystem:

  • Pros
    • A comprehensive collection of tools that are well-integrated and streamlined.
    • Integrated with Visual Studio Code, which is fast, modern, and user-friendly.
    • The availability of third-party modules helps you focus on designing and developing the more important parts of your application rather than reinventing the wheel!
    • The solution’s modularity helps you keep your application organized from a source code perspective and makes it easy for teams to collaborate on projects.
    • The solution is updated regularly with new features and bug fixes, which gives you confidence that you’re working with a robust and up-to-date ecosystem.
  • Cons

So, overall, this is my verdict:

The nRF Connect SDK is a pleasure to work with, and its advantages far outweigh the challenges you may encounter at the beginning of the learning journey. Once you get used to it, you want to keep on using it for every project from thereon!

Friday, June 7, 2024

Easy Setup Guide for Bluetooth Low Energy on Android Platform

 

1. Introduction
Welcome aboard! If you've ever wondered about the immense potential of Android BLE apps, you're in the right place. Bluetooth Low Energy (BLE) has revolutionized the way devices connect and communicate, opening up a vast range of possibilities.

Why am I diving into the world of Android BLE apps? Because it's not just about technology – it's about the potential impact of this technology in our daily lives. Whether you're driven by curiosity, eager to create the next big thing, or simply want to understand the technology that surrounds you, this blog post should resonate with you.

Together, we'll unravel the inner workings of Android BLE apps. I'll guide you through BLE's intricacies and show you how to build apps that stand out. From conserving energy to ensuring secure communication, I'll equip you with the tools to craft powerful Android BLE applications.

2. Understanding Bluetooth Low Energy (BLE)
The world relies on connectivity more than ever, and Bluetooth Low Energy (BLE) has become a key player in enabling seamless communication between devices. But what exactly is BLE, and how does it differ from traditional Bluetooth?

2.1. What is Bluetooth Low Energy?
Before we delve into Bluetooth Low Energy, let's briefly touch on the basics of Bluetooth technology. Bluetooth is a wireless communication protocol that allows devices to exchange data over short distances. It was initially designed to connect peripherals like keyboards, mice, and headsets to computers and mobile devices.

2.2. BLE vs. Classic Bluetooth
Traditional Bluetooth, often referred to as "Classic" Bluetooth, served its purpose well, but it had its limitations. One of the primary challenges was its relatively high power consumption, making it unsuitable for devices that need to conserve energy.

Bluetooth Low Energy, often abbreviated as BLE, is a wireless communication technology optimized for low power consumption. Introduced with the Bluetooth 4.0 specification (also known as Bluetooth 4.0 Low Energy), BLE addresses the limitations of classic Bluetooth, particularly its high power usage. This makes BLE ideal for devices that need to conserve battery life, such as wearables, health monitors, and even Bluetooth Low Energy beacons.

2.3. Applications of Bluetooth Low Energy
The development of BLE has opened doors for innovation in various fields:

Wearables and Fitness Trackers: BLE's low power consumption allows wearables to stay connected for extended periods without frequent charging.

Smart Home Devices: BLE plays a role in connecting smart home devices like thermostats and lights, enabling them to communicate with each other and central hubs efficiently.

Healthcare Applications: BLE can be used in medical devices for data transmission, such as monitoring heart rate or blood pressure.

Bluetooth Low Energy Beacons: These small transmitters leverage BLE to broadcast signals for location-based services and proximity marketing.

3. Setting up the BLE Android app 

3.1. Initialization 

First, we will create the BluetoothHandler class which is initialized with a Context and an optional OMRON instance. The Context is essential for Bluetooth operations within the Android environment, while OMRON is an external library that enables communication with OMRON health devices. 

internal class BluetoothHandler private constructor(private val context: Context, private val omron: OMRON?) { 

    // ... 

} 

 

3.2. Bluetooth Central Management 

The central aspect of the 'BluetoothHandler' class is the management of BLE central operations. It utilizes the 'BluetoothCentralManager' from the 'com.welie.blessed' library to handle Bluetooth device connections, disconnections, and scanning. 

central = BluetoothCentralManager(context, bluetoothCentralManagerCallback, Handler(Looper.getMainLooper())) 

3.3. Device Discovery and Connection 

The 'BluetoothHandler' class is responsible for discovering nearby BLE health devices and establishing connections. When a peripheral device is discovered, it processes the device information, including its type, and decides whether to connect to it. 

override fun onDiscoveredPeripheral(peripheral: BluetoothPeripheral, scanResult: ScanResult) { 

    // ... 

} 

 

3.4. Device Pairing and Unpairing 

The 'BluetoothHandler' class facilitates the pairing and unpairing of health devices. It responds to pairing and unpairing requests through the 'deviceToPair' and 'deviceToUnpair' subjects.  

deviceToPair.subscribe { 

    central?.apply { 

        startPairingPopupHack() 

        autoConnectPeripheral(getPeripheral(it.mac), peripheralCallback) 

        connectPeripheral(getPeripheral(it.mac), peripheralCallback) 

        createBond(getPeripheral(it.mac), peripheralCallback) 

    } 

}.disposeBy(compositeDisposable) 

 

deviceToUnpair.subscribe { 

    central?.removeBond(it.mac) 

}.disposeBy(compositeDisposable) 

 

3.5. Data Transfer 

For specific devices like OMRON health devices, data transfer is initiated by the 'BluetoothHandler' class. It ensures that data transfer is performed at the right intervals. 

handler.postDelayed({ 

    omron?.performDataTransfer(peripheralDevice) 

    transferOmronData = true 

}, PERFORM_OMRON_TRANSFER) 

 

3.5. Data Parsing 

The 'BluetoothHandler' class is responsible for parsing the data received from connected devices. It distinguishes between various types of measurements such as blood pressure, temperature, heart rate, pulse oximetry, glucose, and more. 

override fun onCharacteristicUpdate( 

    peripheral: BluetoothPeripheral, value: ByteArray, characteristic: BluetoothGattCharacteristic, status: GattStatus 

) { 

    // ... 

} 

 

3.6. Broadcasting Measurements 

Once data is parsed, the 'BluetoothHandler' class broadcasts these measurements to the application, allowing it to display or store the health data as needed.  

private fun sendMeasurement(intent: Intent, peripheral: BluetoothPeripheral) { 

    if (healthDevices?.contains(peripheral.address) == true || peripheral.bondState == BondState.BONDED) { 

        intent.putExtra(MEASUREMENT_EXTRA_PERIPHERAL, peripheral.address) 

        context.applicationContext.sendBroadcast(intent) 

    } 

} 

 

4. Conclusions 

Exploring the world of Android BLE apps has uncovered the transformative potential of Bluetooth Low Energy. BLE's energy efficiency has revolutionized device connectivity, fueling innovations in wearables, health tech, and IoT. 

The journey through building an Android BLE app showcased the crucial role of the BluetoothHandler class in managing Bluetooth operations, device connections, and data transfer. It highlighted BLE's ability to enable precise health data exchange efficiently. 

This exploration emphasizes how BLE empowers applications to seamlessly interpret device data, providing valuable insights for users. The journey underscores the fusion of technology and purpose, driving the creation of impactful, user-centric applications. 
 
Exploring Bluetooth Low Energy Further 

With its focus on low power consumption, BLE has become a cornerstone of our interconnected world. If you're interested in delving deeper, you can explore topics like: 

  • Bluetooth Low Energy Devices: Learn about the different types of devices that utilize BLE technology. 

  • Bluetooth Low Energy Communication Protocol: Understand the technical details of how BLE devices communicate with each other. 

  • Bluetooth Low Energy with Arduino: Explore how to integrate BLE functionalities into your Arduino projects (if applicable to your interests). 



In conclusion, Android BLE apps stand as a testament to the boundless opportunities for innovation, shaping a future where efficient connectivity drives technological advancement.