The Garden

ProjectsApps and devices I have built, for clients and for myselfProductsIdeas I own, build and ship myselfBlogLonger writing about building apps, devices and productsNotesLoose notes on things I'm still learning
← Blog/seedling

A tiny device that buzzes when I slouch

A XIAO nRF52840 Sense, a tiny battery, a plastic shell and a haptic motor, plus the BLE link that sends my posture to a Jetpack Compose app.

Planted 14 Mar 20266 min read
#iot#ble#android#kotlin#hardware
Assumed audienceMakers who want to build a small wearable, and Android developers who have never talked to a device over Bluetooth Low Energy.

I sit at a desk all day, and by evening I'm folded over my keyboard like a question mark. Reminders on my phone didn't work. I'd dismiss them and keep slouching.

So I'm building something I can't ignore: a coin-sized device that sticks to my upper back and buzzes every time I slouch. It's still a work in progress, so this post is a build log, not a finished guide.

The hardware

  • Seeed XIAO nRF52840 Sense. A thumbnail-sized board with Bluetooth Low Energy and a built-in 6-axis IMU (accelerometer + gyroscope). The IMU is what tells me which way the device is tilted.
  • A small LiPo battery soldered to the battery pads on the back of the board. The XIAO has a charger built in, so the whole thing charges over USB-C.
  • A small vibration motor for the haptic pulse.
  • A plastic shell I made to hold it all, about the size of a coin.
  • Medical tape to stick it to my upper back, between the shoulder blades.

How it knows I'm slouching

When you sit straight, your upper back is close to vertical. When you slouch, it tips forward. The device tips with it.

The accelerometer always feels gravity. So by looking at how gravity splits across the device's axes, I can work out its tilt angle, no matter how fast or slow I lean. When the angle goes past a threshold, the motor pulses, and I sit up.

posture.ino
#include <ArduinoBLE.h>
#include "LSM6DS3.h"
 
LSM6DS3 imu(I2C_MODE, 0x6A);
 
BLEService postureService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
BLEShortCharacteristic angleChar("6e400003-b5a3-f393-e0a9-e50e24dcca9e",
                                 BLERead | BLENotify);
 
const int SLOUCH_DEG = 20;
 
int tiltDegrees() {
  float ax = imu.readFloatAccelX();
  float az = imu.readFloatAccelZ();
  // Which axes to use depends on how the board sits in the shell
  return (int)(atan2(ax, az) * 180.0 / PI);
}
 
void setup() {
  imu.begin();
  BLE.begin();
  BLE.setLocalName("Posture");
  BLE.setAdvertisedService(postureService); // so the app can find it
  postureService.addCharacteristic(angleChar);
  BLE.addService(postureService);
  BLE.advertise();
}
 
void loop() {
  BLE.poll();
  int angle = tiltDegrees();
  angleChar.writeValue((short)angle); // notifies the app if it's subscribed
  if (abs(angle) > SLOUCH_DEG) pulseMotor();
  delay(500);
}

pulseMotor() switches the vibration motor on for a short moment. The important part: the device does its job on its own. The buzz doesn't need the phone. Bluetooth is for seeing the data, not for the core feature.

BLE in plain words

Bluetooth Low Energy looks scary from the outside (UUIDs, GATT, descriptors, status 133), but there are only a few ideas underneath.

Two roles. The device is the peripheral: every few hundred milliseconds it advertises, a tiny packet saying "I'm here, and here's what I offer." The phone is the central: it scans, finds the device and connects.

GATT, a tiny folder of values. Once connected, the device shows its data as a small tree:

  • A service is a folder, like "Posture service". It has a UUID.
  • A characteristic is a value inside it, like "tilt angle". It has a UUID too, plus properties: read, write or notify.
  • A descriptor is a setting on a characteristic. The one you'll meet is the CCCD (0x2902). Writing to it switches notifications on.

Notify is the key one for a wearable. Instead of the phone asking "what's the angle now?" again and again, the device pushes each new value. Less radio time, less battery.

The app side: Jetpack Compose + BLE

The companion app I'm building in Kotlin and Jetpack Compose shows my live posture angle and how often I slouched. Here's the BLE core of it.

1. Permissions

Since Android 12, BLE has its own runtime permissions, and you don't need location if you promise not to use scans for it:

AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"
    android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

2. Scan only for the device

val scanner = bluetoothAdapter.bluetoothLeScanner
 
val filter = ScanFilter.Builder()
    .setServiceUuid(ParcelUuid(POSTURE_SERVICE_UUID))
    .build()
 
val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        scanner.stopScan(this) // found it, stop draining the battery
        connect(result.device)
    }
}
 
scanner.startScan(listOf(filter), ScanSettings.Builder().build(), scanCallback)

Filtering by the service UUID means the app ignores every other Bluetooth thing in the room.

3. Connect, subscribe, read the angle

private val _angle = MutableStateFlow<Int?>(null)
val angle: StateFlow<Int?> = _angle
 
val gattCallback = object : BluetoothGattCallback() {
 
    override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
        when (newState) {
            BluetoothProfile.STATE_CONNECTED -> gatt.discoverServices()
            BluetoothProfile.STATE_DISCONNECTED -> gatt.close() // always free it
        }
    }
 
    override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
        val char = gatt.getService(POSTURE_SERVICE_UUID)
            ?.getCharacteristic(ANGLE_UUID) ?: return
        gatt.setCharacteristicNotification(char, true)
        gatt.writeDescriptor(
            char.getDescriptor(CCCD_UUID),
            BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE,
        )
    }
 
    override fun onCharacteristicChanged(
        gatt: BluetoothGatt,
        characteristic: BluetoothGattCharacteristic,
        value: ByteArray,
    ) {
        // The device sends a signed 16-bit number, little-endian
        _angle.value = ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).short.toInt()
    }
}

setCharacteristicNotification alone is not enough. It only tells Android to listen. Writing the CCCD tells the device to start sending.

4. Show it in Compose

The BLE code lives in a repository. The ViewModel exposes angle as a StateFlow, and the screen just collects it:

@Composable
fun PostureScreen(viewModel: PostureViewModel) {
    val angle by viewModel.angle.collectAsStateWithLifecycle()
 
    Text(
        text = angle?.let { "$it°" } ?: "Connecting…",
        style = MaterialTheme.typography.displayLarge,
        color = if ((angle ?: 0).absoluteValue > SLOUCH_DEG) Color.Red else Color.Unspecified,
    )
}

Things BLE teaches you the hard way

  • Callbacks run on a Binder thread, not the main thread. Push values into a StateFlow and let the UI collect them.
  • Status 133 (GATT_ERROR) is Android's famous "something went wrong". It often means an old connection was never closed. Call gatt.close() on every disconnect, wait a moment, then retry.
  • Tie the connection to the lifecycle. Keep it in a repository or service, not in an Activity that's about to be destroyed.

What's next

This is a seedling, and I'll keep updating it as the device grows:

  • Photos of the board, the shell and how it sits on the back.
  • Ignoring short leans (reaching for a cup isn't slouching), so it only buzzes after a few seconds.
  • Battery life numbers, once I've measured them.
  • Slouch history and daily stats in the app.