
CodeCell includes a BNO085 3-axis accelerometer that measures movement and orientation in space. In this guide, you’ll learn how to read acceleration values and detect shaking — triggering the onboard LED whenever motion is detected.
An accelerometer measures changes in speed and direction (acceleration) across three axes:
Even when still, CodeCell feels gravity, the Z-axis will show about 9.81 m/s², Earth’s gravitational acceleration.
To start reading motion data, initialize and call:
myCodeCell.Init(MOTION_ACCELEROMETER); // Enable accelerometer
myCodeCell.Motion_AccelerometerRead(x, y, z); // Read acceleration values
This example prints live acceleration data for each axis. Try moving or tilting CodeCell to see how values change.
#include <CodeCell.h>
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_ACCELEROMETER); // Initialize accelerometer
}
void loop() {
if (myCodeCell.Run(10)) { // Run loop at 10 Hz
myCodeCell.Motion_AccelerometerRead(x, y, z);
Serial.print("X: "); Serial.print(x);
Serial.print(" Y: "); Serial.print(y);
Serial.print(" Z: "); Serial.println(z);
}
}
This example calculates total acceleration and turns the LED red when CodeCell is shaken above a set threshold.
#include <CodeCell.h>
#include <math.h> // For sqrt()
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
const float SHAKE_THRESHOLD = 15.0; // Adjust for sensitivity
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_ACCELEROMETER); // Enable accelerometer
}
void loop() {
if (myCodeCell.Run(10)) { // Run at 10 Hz
myCodeCell.Motion_AccelerometerRead(x, y, z);
// Calculate total acceleration magnitude
float totalAcceleration = sqrt(x * x + y * y + z * z);
Serial.print("Total Acceleration: ");
Serial.println(totalAcceleration);
if (totalAcceleration > SHAKE_THRESHOLD) {
Serial.println("Shake detected!");
myCodeCell.LED(255, 0, 0); // Red LED for shake
delay(500);
}
}
}
By combining all three axes into a single totalAcceleration value, you can easily detect shakes in any direction. If it exceeds 15.0 m/s², the onboard LED lights up red for 0.5 seconds.
Join our Community ~ Be the first to know about new products and get exciting deals!
© 2025 Microbots.