A smart dice with a XIAO nRF52840 Sense, Web Bluetooth and three.js
This is a dice that knows which face is up.
Code: smart-dice on GitHub
This is a dice that knows which face is up. Roll it on the table, and a web page shows a 3D die that tilts as you pick it up and lands on the same number a moment after the real one does.
Almost all of it is one board: a Seeed Studio XIAO nRF52840 Sense. It’s 21 × 17.8 mm and carries a Bluetooth chip, a 6-axis motion sensor, a microphone and a LiPo charger. Add a 50 mAh LiPo, a push button and a 3D-printed case designed in Fusion, and that’s the whole parts list.
This post walks through the parts of the code that needed the most thought. The full source is on GitHub.
Pick the right board package
Seeed publishes two Arduino board packages with nearly the same name: Seeed nRF52 Boards and Seeed nRF52 mbed-enabled Boards. Seeed’s wiki recommends the first for low-power Bluetooth and the second for machine learning and the IMU and microphone examples.
This project uses the mbed-enabled one, with the ArduinoBLE library. Select the board under the other package and the build fails with undefined reference to HCITransport, which says nothing about board packages. The IMU library matters too: it has to be Seeed Arduino LSM6DS3. The libraries with similar names are for other boards.
The board is also sold for TinyML, with that microphone and the motion sensor. This build only uses the accelerometer.
Which face is up
When the dice is still, the only force the accelerometer feels is gravity. Whichever axis reads close to 1 g is pointing up, and that axis tells you the face:
const float FACE_THRESHOLD_G = 0.8;
uint8_t faceFromGravity(float ax, float ay, float az) {
if (az > FACE_THRESHOLD_G) return 1;
if (ax > FACE_THRESHOLD_G) return 2;
if (ay > FACE_THRESHOLD_G) return 3;
if (ay < -FACE_THRESHOLD_G) return 4;
if (ax < -FACE_THRESHOLD_G) return 5;
if (az < -FACE_THRESHOLD_G) return 6;
return 0; // on an edge, or moving
}
The numbering follows a real die: opposite faces add up to 7, and the top of the board is face 1. A threshold of 0.8 g means a face still counts when the dice leans up to about 37°, which is plenty for a dice resting on a slightly uneven table.
A single reading isn’t enough, though. Mid-roll, an impact can push one axis past 0.8 g for an instant. So a face only counts as stable once it has held for 300 ms:
uint8_t face = faceFromGravity(ax, ay, az);
if (face != lastFace) {
lastFace = face;
faceSinceMs = now;
}
bool stable = face != 0 && (now - faceSinceMs) >= STABLE_AFTER_MS; // 300 ms
This code assumes the sensor’s axes line up with the dice’s faces. That’s a mechanical requirement as much as a software one: the case has to hold the board flat and square to the walls. A board mounted at an angle eats into that 37° margin.
One small packet, 20 times a second
The board could send just the face number. Instead, it sends the full gravity reading as well, so the 3D die on the page can follow the real one while it’s still moving:
struct __attribute__((packed)) StatePacket {
int16_t ax; // milli-g
int16_t ay;
int16_t az;
uint8_t face; // 1 to 6, 0 = no clear face
uint8_t stable; // 1 once the face has held for 300 ms
uint8_t sleepIn; // seconds until auto sleep, 255 = off
};
Three details make this easy to read in JavaScript:
- packed stops the compiler adding padding, so the struct is exactly 9 bytes.
- Integers, not floats. Acceleration in milli-g fits in an int16, and it’s simpler to decode.
- 9 bytes fits in one notification. With Bluetooth’s default packet size, a notification carries up to 20 bytes.
The nRF52840 is little-endian, so the browser reads it with a DataView and true for little-endian:
export function parseState(view) {
if (view.byteLength < STATE_PACKET_SIZE) {
throw new RangeError(`State packet must be ${STATE_PACKET_SIZE} bytes, got ${view.byteLength}`);
}
const sleepIn = view.byteLength >= STATE_PACKET_FULL_SIZE ? view.getUint8(8) : SLEEP_IN_OFF;
return {
ax: view.getInt16(0, true) / MILLI_G_PER_G,
ay: view.getInt16(2, true) / MILLI_G_PER_G,
az: view.getInt16(4, true) / MILLI_G_PER_G,
face: toFace(view.getUint8(6)),
stable: view.getUint8(7) === 1,
sleepIn: sleepIn === SLEEP_IN_OFF ? null : sleepIn,
};
}
The sleepIn byte was added later, so the parser still accepts the older 8-byte packet. Treat a binary protocol like an API: the firmware and the page get updated at different times, and the reader has to cope with both.
A long press to turn it on and off
A dice has no room for a slide switch, so one push button does it: hold for 2 seconds to turn on, hold again to turn off. “Off” is the nRF52840’s System OFF mode, where almost everything stops and only a pin change can wake the chip. It’s also the part of the firmware with the most edge cases.
Waking up is a reset. When the button wakes the chip from System OFF, it starts again from setup(), after the bootloader has run. By then, a quick tap is already over, so reading the button tells you nothing. The firmware asks the chip why it reset instead:
bool wokeFromButton() {
uint32_t pin = BUTTON_NRF_PIN;
NRF_GPIO_Type* port = (pin >= 32) ? NRF_P1 : NRF_P0;
uint32_t mask = 1UL << (pin & 31);
bool woke = (NRF_POWER->RESETREAS & POWER_RESETREAS_OFF_Msk) || (port->LATCH & mask);
NRF_POWER->RESETREAS = POWER_RESETREAS_OFF_Msk; // these bits stay set until cleared
port->LATCH = mask;
return woke;
}
If it woke from the button, the button must then be held for the full 2 seconds, or the dice goes straight back to sleep. A bump in a bag doesn’t turn it on.
Arduino pin numbers aren’t chip pin numbers. D1 is a board label. The register code above needs the nRF52840’s own pin number, and the two board packages convert it differently:
#if defined(ARDUINO_ARCH_MBED)
#define BUTTON_NRF_PIN ((uint32_t)digitalPinToPinName(BUTTON_PIN))
#else
#define BUTTON_NRF_PIN ((uint32_t)g_ADigitalPinMap[BUTTON_PIN])
#endif
The press that turns it on must not turn it off. When setup() finishes, your finger is still on the button. A buttonArmed flag ignores the button until it has been released once, so the same press can’t immediately start the power-off timer.
Release before you sleep. This is the bug that’s easiest to write:
void shutDownAndSleep() {
ledsForcedOff = true;
allLedsOff(); // pin levels are kept in System OFF
// ...tell a connected page, then stop Bluetooth...
BLE.stopAdvertise();
BLE.end();
imu.writeRegister(0x10, 0x00); // CTRL1_XL = 0: accelerometer off
// Wait for release, or the low-level wake fires immediately.
waitForButtonRelease();
delay(BUTTON_DEBOUNCE_MS);
enterSystemOff();
}
The wake condition is “the button pin is low”. Go to sleep while the finger is still pressing, and that condition is already true, so the chip wakes up again straight away. The dice looks like it simply refuses to turn off.
enterSystemOff() arms the pin with nrf_gpio_cfg_sense_input(…, NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW) and then writes NRF_POWER->SYSTEMOFF = 1. With the other board package, where Nordic’s SoftDevice runs Bluetooth, you have to ask the SoftDevice with sd_power_system_off() instead, and the code handles both.
Sleeping without the button
People forget to turn dice off. So there’s a second, softer sleep: after 60 seconds without movement (3 minutes while a page is connected), the board tells the page, disconnects, stops advertising and checks the accelerometer only twice a second. Picking it up wakes it, because a change of more than 0.25 g on any axis counts as movement.
The sleepIn byte in the packet counts down to that moment, so the page can say “Sleeping in 20 s” before it happens, instead of the connection just dropping.
Wiring with micro wires
There’s very little wiring, but it’s tiny:
- Battery to the BAT+ and BAT− pads on the underside of the board. Check polarity twice: the board has no reverse-polarity protection, and LiPo connectors don’t follow one standard. If you cut a connector off, cut one wire at a time so the cut ends never touch.
- Button between D1 and GND. The firmware turns on the pin’s internal pull-up, so no resistor is needed.
With wires this thin, tin the pads and the wire ends first, then join them with a quick touch of the iron. Cover each joint so nothing can short when the case closes, and fix the wires so a pull lands on the case, not on the solder joint.
The board charges the battery whenever USB-C is connected, at 50 mA by default. For a 50 mAh cell that’s already a 1C charge, so don’t enable the board’s 100 mA mode. If you later add a battery-level reading, read Seeed’s wiki on P0.14 first: it warns that setting that pin high while charging can damage the battery-sense pin.
Designing the case in Fusion
The case followed the same approach as my rover: model the parts first, then draw the body around them. Three things mattered most for a dice:
- The board sits flat and square, for the face detection described above.
- The USB-C port stays reachable, for charging and for uploads. When an upload won’t start, a double-tap on the board’s reset button puts it into bootloader mode, so that button needs to be reachable too.
- The weight sits as close to the centre as possible. The battery and the board aren’t evenly spread, and a dice with an off-centre weight isn’t a fair dice. It’s fine for a demo. For a real game, it’s worth knowing.
The fits follow the same rules as any printed part: make clearance a parameter, and test-print the button hole before printing the whole case.
The web page: Web Bluetooth
The browser connects to the dice directly, with no app and no pairing in the system settings:
export async function connect({ onState, onDisconnect }) {
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: [SERVICE_UUID] }],
});
device.addEventListener('gattserverdisconnected', onDisconnect);
const { gatt } = device;
try {
const server = await gatt.connect();
const service = await server.getPrimaryService(SERVICE_UUID);
const characteristic = await service.getCharacteristic(STATE_UUID);
characteristic.addEventListener('characteristicvaluechanged', () => {
onState(parseState(characteristic.value));
});
await characteristic.startNotifications();
} catch (error) {
// Do not leave a half-open connection behind.
device.removeEventListener('gattserverdisconnected', onDisconnect);
gatt.disconnect();
throw error;
}
// ...
}
A few rules come with Web Bluetooth:
- Chrome and Edge only. It doesn’t work in Safari, Firefox or any iPhone browser.
- It must start from a click. requestDevice() only works from a user gesture, so the page has a Connect button.
- It needs a secure page. The dashboard is deployed to GitHub Pages, which serves it over HTTPS, by a GitHub Actions workflow.
One small detail I like: connecting doesn’t count as a roll. If the dice is already resting on a 4 when the page connects, the roll history doesn’t get a 4 added. Without a board, the number keys 1 to 6 act as a fake dice, which makes the page easy to work on.
three.js: a die that follows the real one
The 3D die is driven by the same gravity reading the board uses. The first problem is that the two don’t agree on which way is up. The sensor uses Z for up, and three.js uses Y:
// Sensor +X is scene +X, sensor +Z is scene +Y, and sensor +Y is scene -Z.
export function sensorToSceneUp(ax, ay, az) {
const length = Math.hypot(ax, ay, az);
if (!(length >= MIN_GRAVITY_G)) return null; // free fall: don't trust it
return [ax / length, az / length, -ay / length];
}
The minus sign matters. Swapping two axes on its own would mirror the scene. Negating one of them turns the swap into a proper rotation, a quarter turn around X.
From there, the die has a target orientation. While the dice is moving, the target follows the live gravity reading. Once the face is stable, it snaps to that face pointing straight up:
function updateTarget() {
if (reading.stable && reading.face !== NO_FACE) {
target.setFromUnitVectors(FACE_NORMALS[reading.face], UP);
return;
}
const up = sensorToSceneUp(reading.ax, reading.ay, reading.az);
if (up) target.setFromUnitVectors(scratchUp.set(...up), UP);
}
The die doesn’t jump to the target. A small spring turns it towards the target every frame, with a little overshoot, which is what makes it feel physical. When the browser asks for reduced motion, the same spring is critically damped, so it moves straight there without wobbling. A roll that lands also gets a small hop and a glow in the face’s colour.
The face textures are drawn on a
One thing to keep in sync: the face numbering lives in three places. The firmware’s faceFromGravity, the gravity table in faces.js, and the order of the cube’s six materials. I checked all six faces with three.js r187: each texture lands on top exactly when the board reports that number.
Shipping three.js without a bundler
The dashboard is plain HTML and JavaScript. To make the built page work when opened straight from disk, a small Python script joins the modules into one script. That needs three.js as a classic script that defines a global THREE, and three.js no longer ships one. So the repo builds a cut-down copy of r187 with esbuild, containing only the 19 pieces the page uses.
What’s next
- Battery level on the page, with the P0.14 warning above in mind.
- Fewer packets. Twenty a second is what makes the live tilt smooth. Sending only when something changes would save power.
- The parts this build doesn’t use yet. The board ships with a microphone and is sold for TinyML. Shake-to-roll as a trained gesture, or a knock to wake it, would both fit on this board.