Inside your CodeCell is a BNO085 3-axis accelerometer, a tiny sensor that measures movement. With just a few lines of code, you can detect shaking and even trigger an LED light when movement is detected! Let's break it down step by step.
An accelerometer measures acceleration - how fast something is speeding up or slowing down. It detects:
It even feels gravity! When CodeCell is still, the Z-axis will show a value close to 9.81 m/s², which is Earth's gravity.
First, let's start by reading real-time movement values from CodeCell's onboard accelerometer. This code will show how much CodeCell is moving in each direction:
#include <CodeCell.h>
CodeCell myCodeCell;
float x = 0.0; // X-axis acceleration
float y = 0.0; // Y-axis acceleration
float z = 0.0; // Z-axis acceleration
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_ACCELEROMETER); // Initialize the accelerometer
}
void loop() {
if (myCodeCell.Run(10)) { // Run at 10 times per second (10Hz)
myCodeCell.Motion_AccelerometerRead(x, y, z); // Read motion values
Serial.print("X: "); Serial.print(x);
Serial.print(" Y: "); Serial.print(y);
Serial.print(" Z: "); Serial.println(z);
}
}
Now, let’s detect when CodeCell is shaken and use the onboard RGB LED to signal it.
This program will turn the LED red if a shake is detected.
#include <CodeCell.h>
#include <math.h> // Needed for square root calculations
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
const float SHAKE_THRESHOLD = 15.0; // Adjust this value for sensitivity
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_ACCELEROMETER); // Initialize accelerometer
}
void loop() {
if (myCodeCell.Run(10)) { // Check every 100ms (10Hz)
myCodeCell.Motion_AccelerometerRead(x, y, z); // Read accelerometer data
// Calculate total movement strength (vector magnitude)
float totalAcceleration = sqrt(x * x + y * y + z * z);
Serial.print("Total Acceleration: ");
Serial.println(totalAcceleration); // Show acceleration strength
// If the acceleration is stronger than the threshold, it's a shake!
if (totalAcceleration > SHAKE_THRESHOLD) {
Serial.println("Shake detected!");
myCodeCell.LED(255, 0, 0); // Turn LED red
delay(500); // Keep LED on for 0.5 seconds
} else {
//Not shaking
}
}
}
Instead of checking X, Y, and Z separately, we combine them into a single value:
This tells us how much CodeCell is moving overall, no matter the direction. If totalAcceleration
jumps above 15.0, we assume CodeCell is being shaken. The onboard RGB LED turns red for 0.5 seconds to signal the shake.
Now that you can detect movement, here are some fun challenges:
By understanding motion sensing, you're learning the same technology used in smartphones, drones, and rockets! 🚀
Join our Community ~ Be the first to know about new products and get exciting deals!
© 2025 Microbots.