Mobile · IoT · Embedded Systems
AtomBrick: ESP32 BLE Motor Controller to KMP Mobile App
BLE motor control across embedded and mobile is two separate protocol stacks with one shared contract. Build AtomBrick end to end using ESP32, Kable, and Kotlin Multiplatform.
- Published
- Reading
- 8 min
- Author
- Fidelis Uwem Joseph
Series · Part 1 of 4BLE & AtomBrick
- AtomBrick: ESP32 BLE Motor Controller to KMP Mobile App
- BLE GATT Profile Design for Hardware Control: AtomBrick
- ESP32 BLE Passkey Pairing, Bonding, and Encryption
- Kotlin Multiplatform BLE with Kable, Koin, and Compose
AtomBrick is a Bluetooth motor controller. An ESP32 acts as a BLE peripheral driving up to five DC motors. A Kotlin Multiplatform app on Android and iOS connects, authenticates via passkey, and sends motor commands. This post walks the full stack, covering firmware, command protocol, and the mobile layer, with specific attention to where the two sides meet.
Prerequisites
- Working knowledge of the Arduino framework and ESP32 GPIO/PWM
- Android and Kotlin development experience
- PlatformIO installed for firmware flashing
- Basic familiarity with Kotlin Multiplatform and Compose
Background
Building a Bluetooth motor controller involves two independent protocol stacks that must agree on one shared contract: the bytes written to each BLE characteristic. The ESP32 side defines the GATT profile and the command encoding. The mobile app side must match it exactly. Any drift between the two produces silent failures: a write succeeds at the BLE layer but the motor does nothing because the command byte is wrong.
The AtomBrick design keeps this contract minimal. Two bytes per command, four command types, one characteristic per motor. That is the entire protocol.
Implementation
1. Hardware: MX1508 motor channels
Each channel uses a dual H-bridge MX1508 driver controlled via two ESP32 GPIO pins with PWM. Five channels use ten GPIO pins total.
MX1508 motorA(INT1_A=12, INT2_A=13, CH1=0, CH2=1);MX1508 motorB(INT1_B=27, INT2_B=26, CH1=0, CH2=1);MX1508 motorC(INT1_C=25, INT2_C=33, CH1=0, CH2=1);MX1508 motorD(INT1_D=32, INT2_D=35, CH1=0, CH2=1);MX1508 motorE(INT1_E=34, INT2_E=39, CH1=0, CH2=1);motorGo(speed) accepts 0 to 255. motorRev(speed) reverses polarity. motorStop() brakes.
2. BLE server: service and security
The ESP32 exposes one service with six characteristics: five for motor control and one for device naming.
Service: 0000180D-0000-1000-8000-00805F9B34FBMotor 1: 00002A31-... READ | WRITE | NOTIFYMotor 2: 00002A32-... READ | WRITE | NOTIFYMotor 3: 00002A33-... READ | WRITE | NOTIFYMotor 4: 00002A34-... READ | WRITE | NOTIFYMotor 5: 00002A35-... READ | WRITE | NOTIFYName: 00002A36-... READ | WRITEPairing uses a static six-digit PIN with MITM protection and bonding so the PIN is entered once per phone, not once per connection:
BLESecurity *pSecurity = new BLESecurity();pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND | ESP_LE_AUTH_REQ_MITM);pSecurity->setCapability(ESP_IO_CAP_OUT);pSecurity->setStaticPIN(123456);pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);After every disconnect, the firmware resumes advertising automatically in onDisconnect.
3. Command protocol
All motor commands are two bytes written to the motor’s characteristic:
| Byte 0 (command) | Byte 1 (data) | Effect |
|---|---|---|
0x01 | 0x01 / 0x00 | Motor on / off |
0x02 | speed (0 to 127) | Forward at speed |
0x03 | speed (0 to 127) | Reverse at speed |
0x04 | seconds (0 to 60) | Run for duration, then stop |
The firmware dispatches commands 1 to 3 synchronously:
void processMotorCommand(MX1508 &motor, uint8_t cmd, int8_t value) { switch (cmd) { case 1: value == 1 ? motor.motorGo(128) : motor.motorStop(); break; case 2: motor.motorGo(value); break; case 3: motor.motorRev(value); break; default: Serial.printf("Unknown command: %d\n", cmd); }}Command 0x04 (timer) is handled separately in main.cpp because it requires state across loop iterations:
if (command < 4) { processMotorCommand(motorA, command, data);} else { currentMotor = &motorA; timerMotorDuration = min((int)data, 60); motorStartTime = millis(); isMotorRunning = true; currentMotor->motorGo(120);}// In loop(), checked every 100msif (isMotorRunning && currentMotor != nullptr) { unsigned long elapsed = (millis() - motorStartTime) / 1000; if (elapsed >= timerMotorDuration) { currentMotor->stopMotor(); isMotorRunning = false; }}The millis() approach avoids blocking loop() and avoids the overhead of a FreeRTOS task for a single timer. Resolution is approximately 100ms given the delay(100) at the end of loop().
4. Mobile: scan and connect
The BleManager singleton owns the Scanner with a name prefix filter so only AtomBrick devices surface in results:
val scanner = Scanner { filters { match { name = Filter.Name.Prefix("ATOM") } } logging { engine = SystemLogEngine; level = Logging.Level.Events }}MotorViewModel collects the scan flow in viewModelScope and deduplicates by device identifier:
scanJob = scanner.advertisements .onEach { adv -> bluetoothState = bluetoothState.copy( availableDevices = BleManager.updateDevicesList(adv, bluetoothState.availableDevices) ) } .launchIn(viewModelScope)Connection is a suspend call with a 20-second timeout:
peripheral = Peripheral(device.advertisement ?: error("No advertisement"))withTimeout(20_000) { peripheral?.connect() }5. Mobile: write motor commands
The app mirrors the firmware protocol exactly. toggleMotor applies an optimistic UI update and reverts on failure:
fun toggleMotor(motor: Motor, isOn: Boolean) { viewModelScope.launch { _motorState.update { it.copy(motors = it.motors.map { m -> if (m.id == motor.id) m.copy(isOn = isOn) else m })} try { peripheral?.services?.collect { services -> services?.let { peripheral?.write( characteristic = characteristicOf(services[2].serviceUuid, motor.characteristic), data = byteArrayOf(0x01, if (isOn) 0x01 else 0x00), writeType = WriteType.WithResponse ) } } } catch (e: Exception) { _motorState.update { it.copy(motors = it.motors.map { m -> if (m.id == motor.id) m.copy(isOn = !isOn) else m })} } }}Testing and Verification
Firmware: Flash via PlatformIO and monitor serial output. Use nRF Connect to exercise the characteristics directly before involving the app:
[Serial Monitor]BLE Server Ready. Pairing PIN: 123456Device ConnectedAuth OKRaw Value (Hex) A: 01 01 <- toggle onRaw Value (Hex) A: 02 50 <- speed 80 forwardApp on Android: declare and request permissions before scanning:
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" /><uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />App on iOS: add NSBluetoothAlwaysUsageDescription to Info.plist.
Tap the Bluetooth icon on the Motor screen, select the device, enter the PIN, and the motor controls become active. The round-trip from tap to motor motion is under 100ms under normal BLE conditions.
Pitfalls
Production Considerations
The services[2] index for locating the AtomBrick service is fragile: it assumes service enumeration order is stable across firmware versions and iOS vs Android. Find the service by UUID instead:
val service = services?.firstOrNull { it.serviceUuid == TARGET_SERVICE_UUID } ?: return@letThe current service uses SIG-assigned UUIDs (0x180D, 0x2A31 to 0x2A36) which nRF Connect will label as Heart Rate service characteristics. A custom 128-bit UUID makes the service self-documenting and avoids confusion in any generic BLE tool.
Going deeper
The two halves work. This section is about the things that matter once the controller drives real motors on a real bench: pin choices that boot every time, PWM channels that do not interfere, timers on every motor, a failsafe when the phone disappears and power that does not reset the board.
Revisit the pin map
The warning above covers GPIO 34 and 39, but motor D uses GPIO 35, which is also input-only. Two more pins on the current map deserve attention:
- GPIO 12 (motor A) is a strapping pin. Its level at reset selects the flash voltage. If the MX1508 input pulls it high during boot, many modules fail to start, with an endless reset loop as the only symptom.
- GPIO 6 to 11 are wired to the module’s flash and must never be used. The current map avoids them, and any rework should too.
A map that uses only output-capable, non-strapping pins:
| Motor | IN1 | IN2 | LEDC channels |
|---|---|---|---|
| A | 13 | 14 | 0, 1 |
| B | 27 | 26 | 2, 3 |
| C | 25 | 33 | 4, 5 |
| D | 32 | 23 | 6, 7 |
| E | 18 | 19 | 8, 9 |
Give every motor its own PWM channels
Every motor in step 1 is constructed with CH1=0, CH2=1. The ESP32’s LEDC peripheral generates one PWM signal per channel, and every pin attached to a channel outputs that channel’s duty cycle. Five motors on channels 0 and 1 means changing the speed of one motor changes the signal on every motor’s pins. The ESP32 has 16 LEDC channels, enough for five motors at two channels each:
MX1508 motorA(13, 14, 0, 1);MX1508 motorB(27, 26, 2, 3);MX1508 motorC(25, 33, 4, 5);MX1508 motorD(32, 23, 6, 7);MX1508 motorE(18, 19, 8, 9);
MX1508 *motors[] = { &motorA, &motorB, &motorC, &motorD, &motorE };The motors array is used by everything below.
A timer for every motor
The pitfall above notes that only one motor can run a timer. Replace the single pointer with per-motor state and check all of them in loop():
struct MotorTimer { bool active = false; unsigned long startMs = 0; unsigned long durationMs = 0;};MotorTimer timers[5];
void startTimer(int i, uint8_t seconds) { timers[i] = { true, millis(), min((unsigned long) seconds, 60UL) * 1000UL }; motors[i]->motorGo(120);}
void tickTimers() { for (int i = 0; i < 5; i++) { // subtraction keeps working when millis() wraps after ~49 days if (timers[i].active && millis() - timers[i].startMs >= timers[i].durationMs) { motors[i]->motorStop(); timers[i].active = false; } }}Comparing millis() - start >= duration rather than millis() >= start + duration matters for a device that stays powered for weeks: unsigned subtraction gives the right elapsed time even after millis() overflows.
A small bonus of keeping time in milliseconds: the delay(100) at the end of loop() can drop to delay(10), which brings timer resolution down to about 10 ms at no real cost.
Stop everything when the phone goes away
A motor that keeps running after the controlling phone walks out of range is a safety problem, not a convenience problem. Treat a lost connection as “stop”:
volatile bool linkLost = false;
void onDisconnect(BLEServer *pServer) override { linkLost = true; pServer->getAdvertising()->start();}
void loop() { if (linkLost) { linkLost = false; for (auto *m : motors) m->motorStop(); for (auto &t : timers) t.active = false; } tickTimers(); delay(10);}The callback only sets a flag. The motors are stopped from loop(), which keeps driver calls out of the Bluetooth task, the same principle as the deferred rename in the pairing post.
For continuous motion you can go a step further with a dead man’s switch: the app sends a small keep-alive every second while a motor runs, and the firmware stops any motor that has not heard from the app for three seconds. That covers a frozen app, not just a dropped link.
Power the motors separately
DC motors draw a burst of current at start-up, often several times their running current. If they share a supply with the ESP32 without enough capacitance, the supply sags, the ESP32’s brownout detector resets the chip and the phone sees a disconnect. From the app it looks like a Bluetooth problem.
- Power the MX1508 boards from their own supply and connect only the grounds together.
- Put a bulk electrolytic capacitor (a few hundred µF) across the motor supply near the drivers, and a 100 nF ceramic across each motor’s terminals.
- If the serial monitor shows
Brownout detector was triggeredafter a motor starts, the problem is power, not code.
Reconnecting after a power cycle
The wrap-up promises reconnection as a follow-up. The app-side loop, connect with exponential backoff until the device returns, is covered in the Kotlin Multiplatform BLE post. Because the firmware bonds with the phone, a reconnect after a power cycle reuses the stored keys and needs no PIN, as long as the bond still exists on both sides. Combined with the failsafe above, a power cycle mid-session is safe: the motors stop when the link drops and the app reconnects to a device in a known state.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Motor D or E never moves | GPIO 34, 35 or 39 used as outputs | Move to output-capable pins |
| Board resets in a loop at power-on | GPIO 12 pulled high during boot | Move motor A off GPIO 12 |
| Changing one motor’s speed changes others | Motors share LEDC channels | Give each motor its own channel pair |
| Disconnect every time a motor starts | Supply sag triggers brownout reset | Separate motor supply, add bulk capacitance |
| A second timer cancels the first | Single global timer pointer | Per-motor timer state |
| Motors keep running after the phone leaves | No failsafe on disconnect | Stop all motors when the link drops |
Wrapping Up
The complete AtomBrick system is roughly 300 lines of ESP32 firmware and 400 lines of shared Kotlin. The 2-byte command protocol is the contract between them. Keeping it small and explicit meant both sides were straightforward to implement and debug in isolation using nRF Connect before the app was involved.
The rest of the series goes a layer deeper on each side: designing the GATT profile, passkey pairing and bonding on the ESP32, and the Kotlin Multiplatform app. Reconnection after the ESP32 power-cycles mid-session, re-discovering and re-authenticating without user intervention, is the natural next problem.