Black Friday Offer 🔥 Use code BLKFRI at checkout to get 15% OFF on orders above €60!
CodeCell includes a built-in BNO085 3-axis magnetometer, allowing it to sense magnetic fields and determine direction, just like a digital compass.
A magnetometer measures the Earth’s magnetic field along three axes:
These values can be read directly from CodeCell using:
myCodeCell.Motion_MagnetometerRead(x, y, z);
To enable the sensor, initialize magnetometer mode with:
myCodeCell.Init(MOTION_MAGNETOMETER);
Once initialized, CodeCell continuously outputs raw magnetic data that can be used to calculate heading or detect magnetic interference.
This example prints live magnetic field readings (X, Y, Z) to the Serial Monitor.
#include <CodeCell.h>
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_MAGNETOMETER); // Initialize magnetometer
}
void loop() {
if (myCodeCell.Run(10)) { // Run loop at 10 Hz
myCodeCell.Motion_MagnetometerRead(x, y, z);
Serial.print("Mag X: "); Serial.print(x);
Serial.print(" Y: "); Serial.print(y);
Serial.print(" Z: "); Serial.println(z);
}
}
As you rotate or tilt the CodeCell, the X, Y, and Z values will change — helping you visualize magnetic direction and strength.
This example converts magnetometer readings into a compass heading (0°–360°) using the atan2() function.
#include <CodeCell.h>
#include <math.h> // Required for atan2()
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_MAGNETOMETER);
}
void loop() {
if (myCodeCell.Run(10)) {
myCodeCell.Motion_MagnetometerRead(x, y, z);
// Calculate heading in degrees
float heading = atan2(y, x) * (180.0 / M_PI);
if (heading < 0) heading += 360;
Serial.print("Compass Heading: ");
Serial.println(heading);
}
}
The heading represents direction in degrees:
| Heading (°) | Direction |
|---|---|
| 0° (or 360°) | North ↑ |
| 90° | East → |
| 180° | South ↓ |
| 270° | West ← |
Here, the onboard LED changes color depending on which direction CodeCell is facing:
#include <CodeCell.h>
#include <math.h>
CodeCell myCodeCell;
float x = 0.0, y = 0.0, z = 0.0;
void setup() {
Serial.begin(115200);
myCodeCell.Init(MOTION_MAGNETOMETER);
}
void loop() {
if (myCodeCell.Run(10)) {
myCodeCell.Motion_MagnetometerRead(x, y, z);
float heading = atan2(y, x) * (180.0 / M_PI);
if (heading < 0) heading += 360;
// LED color by direction
if (heading >= 315 || heading < 45) {
myCodeCell.LED(0, 0, 255); // Blue → North
} else if (heading >= 45 && heading < 135) {
myCodeCell.LED(0, 255, 0); // Green → East
} else if (heading >= 135 && heading < 225) {
myCodeCell.LED(255, 0, 0); // Red → South
} else {
myCodeCell.LED(255, 255, 0); // Yellow → West
}
Serial.printf("Heading: %.1f°\n", heading);
}
}
Join our Community ~ Be the first to know about new products and get exciting deals!
© 2025 Microbots.