Adafruit Unified Sensor: the event every Adafruit driver fills
Yes. You can use the Adafruit Unified Sensor library online in Mokxi with nothing to install, and the sketch runs in your browser. The example below, "MPU6050 servo stabilizer", runs on the Arduino Uno R3.
Built in on Mokxi: #include <Adafruit_Sensor.h> and it builds, with nothing to install. Free, and no account needed.
What Adafruit Unified Sensor does
Adafruit Unified Sensor drives no chip of its own. It is a shared vocabulary that many Adafruit libraries build on: a struct called sensors_event_t that holds one reading, a struct called sensor_t that describes a sensor, and a base class, Adafruit_Sensor, with getEvent() and getSensor(). An accelerometer, a thermometer and a humidity sensor all hand back the same kind of event, so code that logs or prints readings does not have to care which chip made them.
The event is a union. acceleration, gyro, temperature, relative_humidity, pressure and light share the same few bytes, and the field to read is the one that matches event.type. The units come from the convention, not the chip: meters per second squared for acceleration, degrees Celsius, percent, hectopascals. Constants such as SENSORS_GRAVITY_EARTH (9.80665) help convert to other units.
Plenty of tutorials put #include <Adafruit_Sensor.h> above DHT.h or Adafruit_MPU6050.h out of habit. On a real board it has to be installed, because those libraries list it as a dependency. In Mokxi it is built in, and the drivers that use it include it themselves. The example below is the servo stabilizer, which reads an MPU6050 into three events per pass, one each for acceleration, rotation and temperature.
| Library Manager name | Adafruit Unified Sensor |
|---|---|
| Author | Adafruit |
| Include | #include <Adafruit_Sensor.h> |
| Boards | every board Mokxi compiles for |
| In the simulator | Simulated: it runs against the part the way it does on the bench. |
Install it
It builds on every board Mokxi compiles for.
In Mokxi it is built in: #include <Adafruit_Sensor.h> and the sketch compiles, with no download, no zip and no Library Manager.
On a real board, install "Adafruit Unified Sensor" by Adafruit from the Arduino IDE’s Library Manager (Sketch, Include Library, Manage Libraries), or add Adafruit Unified Sensor to lib_deps in PlatformIO. Mokxi follows the calls of release 1.1.15, so a sketch written here builds there too.
- ESP32-C3
- Arduino Uno
- Arduino Nano
- Arduino Mega 2560
- Arduino Leonardo
- SparkFun Pro Micro
- Arduino Micro
- ESP32-C6
- WCH CH32V003
- ATtiny85
- Raspberry Pi Pico
- Raspberry Pi Pico W
- Seeed XIAO SAMD21
- STM32
- STM32 Nucleo-F411RE
- STM32 Blue Pill
- micro:bit V2
- Arduino Uno R4
- ESP32 DevKit
- ESP32-S3-DevKitC-1
- ESP8266 NodeMCU
- Arduino Pro Mini 3.3 V
- Seeed XIAO ESP32-C3
- ESP32-C3 SuperMini
- Seeed XIAO ESP32-C6
- ESP32-DevKitC V4
- LOLIN32 Lite
- Wemos D1 R32
- Cheap Yellow Display
- TTGO T-Display
- Seeed XIAO ESP32-S3
- Arduino Nano ESP32
- Arduino Nano RP2040 Connect
- Seeed XIAO RP2040
- Waveshare RP2040-Zero
- Arduino Uno R4 WiFi
The calls you will use
In the order a sketch meets them.
sensors_event_t a, g, temp
Declares the reading structs. getEvent() clears each one, stamps its type, sensor ID and millis(), then writes the value into the field for that kind of sensor.
mpu.getEvent(&a, &g, &temp)
A driver with several readings fills several events in one call. Single-reading drivers take one pointer, such as accel.getEvent(&event), and return false when the chip did not answer.
a.acceleration.x
The x axis of an accelerometer event in m/s^2, with .y and .z beside it. A gyroscope event uses gyro.x, gyro.y and gyro.z instead.
float rollG = a.acceleration.y / SENSORS_GRAVITY_EARTH;temp.temperature
Degrees Celsius from a temperature event. relative_humidity, pressure and light are the other single-value fields; read only the one that matches the sensor that filled the event.
accel.getSensor(&sensor)
Fills a sensor_t with the chip’s name, its minimum and maximum values, its resolution and the ID given to the constructor.
sensor_t sensor;
accel.getSensor(&sensor);
Serial.println(sensor.name);
Serial.println(sensor.max_value);accel.printSensorDetails()
Prints that same description to Serial as a block of lines, a quick check in setup() that the expected driver is the one talking.
event.type == SENSOR_TYPE_ACCELEROMETER
Tells which kind of reading an event carries, one of the SENSOR_TYPE_ numbers, useful in code that receives events from more than one driver.
Example: MPU6050 servo stabilizer
On the Arduino Uno R3. It runs in the browser exactly as printed.
// MPU6050 servo stabilizer: a two-axis self-leveling gimbal. Tilt the
// MPU6050 and two servos turn the other way to keep a platform level, the
// way a camera gimbal or a model plane's wing leveler does.
//
// MPU6050 SDA to A4, SCL to A5, VCC to 5V, GND to GND
// servos roll on pin 9, pitch on pin 10, from a separate 5 V supply
// with the grounds joined
//
// TILT FROM GRAVITY. Held still, an accelerometer measures only gravity, so
// the way gravity splits between its three axes tells you the tilt:
//
// roll = atan2(ay, az)
// pitch = atan2(-ax, sqrt(ay*ay + az*az))
//
// That is right on a bench and wrong in a moving model, where every bump
// and turn adds acceleration that is not gravity.
//
// TILT FROM THE GYRO. The gyroscope measures how fast the board is turning,
// in degrees per second. Add that up over time and you also have the tilt,
// smooth and unbothered by bumps, but every tiny error adds up too and the
// angle slowly drifts away.
//
// THE COMPLEMENTARY FILTER uses each for what it is good at: trust the gyro
// from moment to moment, and pull gently toward the accelerometer so the
// drift cannot build up.
//
// alpha = TAU / (TAU + dt)
// angle = alpha * (angle + rate * dt) + (1 - alpha) * accelAngle
//
// TAU is the filter's time constant, a quarter of a second here: after a
// tilt the angle covers about two thirds of the way to the accelerometer's
// answer in TAU, and nearly all of it in four TAU. Working alpha out from
// dt on every pass keeps that true however long a pass takes. Reading the
// sensor and the floating-point math take time too, so a pass is longer
// than the 10 ms delay at the end of loop().
//
// THE SERVOS hold the platform level by turning the same amount the other
// way: 90 degrees is level, so a roll of +20 sends the roll servo to 70.
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Servo.h>
Adafruit_MPU6050 mpu;
Servo rollServo, pitchServo;
const float TAU = 0.25; // the filter's time constant, in seconds
const float DEGREES = 180.0 / M_PI;
// If a servo turns the same way as the tilt on your build, set its entry
// to -1 so it turns the other way.
const int ROLL_DIRECTION = -1;
const int PITCH_DIRECTION = -1;
float roll = 0, pitch = 0; // the filtered tilt, in degrees
unsigned long lastMicros = 0;
unsigned long lastPrint = 0;
void setup() {
Serial.begin(115200);
if (!mpu.begin()) {
Serial.println("no MPU6050 at 0x68: check SDA, SCL and VCC");
while (true) delay(10);
}
rollServo.attach(9);
pitchServo.attach(10);
rollServo.write(90);
pitchServo.write(90);
// Start the filter from the accelerometer, so it does not have to swing
// up from zero at power on.
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
roll = atan2(a.acceleration.y, a.acceleration.z) * DEGREES;
pitch = atan2(-a.acceleration.x, sqrt(a.acceleration.y * a.acceleration.y + a.acceleration.z * a.acceleration.z)) * DEGREES;
lastMicros = micros();
Serial.println("stabilizer: drag the MPU6050 to tilt it");
}
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
// How long since the last pass, in seconds.
unsigned long now = micros();
float dt = (now - lastMicros) / 1000000.0;
lastMicros = now;
// Tilt from gravity alone.
float ax = a.acceleration.x, ay = a.acceleration.y, az = a.acceleration.z;
float accelRoll = atan2(ay, az) * DEGREES;
float accelPitch = atan2(-ax, sqrt(ay * ay + az * az)) * DEGREES;
// The complementary filter. The gyro reads radians per second.
float alpha = TAU / (TAU + dt);
roll = alpha * (roll + g.gyro.x * DEGREES * dt) + (1 - alpha) * accelRoll;
pitch = alpha * (pitch + g.gyro.y * DEGREES * dt) + (1 - alpha) * accelPitch;
// Turn each servo against its tilt, held to its travel.
int rollAngle = constrain(90 + ROLL_DIRECTION * (int)lround(roll), 0, 180);
int pitchAngle = constrain(90 + PITCH_DIRECTION * (int)lround(pitch), 0, 180);
rollServo.write(rollAngle);
pitchServo.write(pitchAngle);
// Report five times a second.
if (millis() - lastPrint >= 200) {
lastPrint = millis();
Serial.print("roll ");
Serial.print(roll, 1);
Serial.print(" pitch ");
Serial.print(pitch, 1);
Serial.print(" -> roll servo ");
Serial.print(rollAngle);
Serial.print(" pitch servo ");
Serial.println(pitchAngle);
}
delay(10);
}Open it in the editor, wired and ready to run · MPU6050 servo stabilizer: the project page
Common errors and how to fix them
fatal error: Adafruit_Sensor.h: No such file or directory
On hardware the header comes from its own package. Open the Library Manager, search for Adafruit Unified Sensor and install it next to the driver. Mokxi ships it already, so the include resolves there with nothing to add.
A temperature prints as 9.81, or some other number that belongs to a different sensor
Because every field shares the same memory, reading temperature from an accelerometer event returns the bytes of acceleration.x. Keep one event variable per reading and read the field that matches it.
error: 'sensors_event_t' does not name a type
The struct is used above the line that brings it in. Put the driver’s include, or Adafruit_Sensor.h itself, at the top of the sketch before any event is declared.
cannot declare variable 'sensor' to be of abstract type 'Adafruit_Sensor'
Adafruit_Sensor is only the base class and cannot be made on its own. Create the driver object, for example Adafruit_ADXL345_Unified, and use Adafruit_Sensor pointers only for what calls such as getTemperatureSensor() return.
Questions and answers
Does a DHT11 sketch need Adafruit_Sensor.h?
In Mokxi, DHT.h uses nothing from it, so the include is harmless and optional. For a real board install it anyway, since the DHT library depends on it and its unified example uses the events.
Why does acceleration come in m/s^2 rather than g?
The unified convention fixes SI units for every driver. Divide by SENSORS_GRAVITY_EARTH to get g, as the stabilizer does before working out its angles.
Projects that use Adafruit Unified Sensor
Built-in projects that include it. Each page has the full sketch and opens in the editor, already wired.
Keep going
Try Adafruit Unified Sensor without installing anything
Open the example, change the sketch, and keep your version in a free account.