CircuitPython code to detect motion of the Seeed XIAO nRF52840 Sense and send Bluetooth Low Energy (BLE) advertisements in the BTHome format when it's moving
MIT License
This project offers CircuitPython code to detect motion of the Seeed XIAO nRF52840 Sense board and send Bluetooth Low Energy (BLE) advertisements in the BTHome format when it's moving.
This allows you to use the Seeed XIAO nRF52840 Sense as an inertial sensor in Home Assistant, as the BLE advertisements in the BTHome format are supported by Home Assistant and automatically discovered when using the BTHome integration. The code uses the unencrypted BTHome v2 format.
Check whether your Bluetooth adapter is recognised by Home Assistant. If you have a built-in Bluetooth adapter, for example on your Raspberry Pi, it should already be recognised on the Settings / Devices & Services / Integrations page. If not, for example if you connect an external Bluetooth adapter via USB, click Add Integration at the bottom right of that page and choose Bluetooth. Confirm with Save that you want to add the recognised adapter.
Click again on Add Integration on the same page and this time choose BTHome. If your board is currently advertising, it will already be recognised here immediately:
Click Submit, assign it to an area if necessary and then click Finish. After that, you can view the device and add the inertial sensor to your dashboard or use it in your automations:
You can change some of the code's parameters by setting the following constants in the beginning:
# Customize the device behavior here
DEVICE_NAME = "XIAO nRF52840 Sense"
INTERVAL = 0.1
SENSITIVITY = 0.01
DEVICE_NAME
is the advertised device name in the BLE packets. INTERVAL
is the interval between the BLE advertisements (in seconds, so 100 ms by default). And SENSITIVITY
is the sensitivity of the gyroscope used to decide when the board is moving. Make this number smaller to detect smaller movements and bigger to detect only larger movements.
The code is a simple example of how you can send BLE advertisements in the BTHome format with CircuitPython. Consult the BTHome format specification for how to adapt this to other sensor types.
Note that this code uses CircuitPython's low-level BLE module _bleio, which is meant for internal use according to its documentation. The code has been tested with CircuitPython 8.0.2, but _bleio's API can change at any time. I decided to use _bleio instead of adafruit_ble because the latter's documentation was unclear.
If you want to learn more about Bluetooth Low Energy development, read my book Develop your own Bluetooth Low Energy Applications for Raspberry Pi, ESP32 and nRF52 with Python, Arduino and Zephyr and the accompanying GitHub repository koenvervloesem/bluetooth-low-energy-applications.
This project is provided by Koen Vervloesem as open-source software with the MIT license. See the LICENSE file for more information.