DepthAI
  • DepthAI Components
    • AprilTags
    • Benchmark
    • Camera
    • Calibration
    • DetectionNetwork
    • Events
    • FeatureTracker
    • Gate
    • HostNodes
    • ImageAlign
    • ImageManip
    • IMU
    • Misc
    • Model Zoo
    • NeuralDepth
    • NeuralNetwork
    • ObjectTracker
    • RecordReplay
    • RGBD
    • Script
    • SpatialDetectionNetwork
    • SpatialLocationCalculator
    • StereoDepth
    • Sync
    • VideoEncoder
    • Visualizer
    • Warp
    • RVC2-specific
  • Advanced Tutorials
  • API Reference
  • Tools
Software Stack

ON THIS PAGE

  • Demo
  • Pipeline
  • Source code

IMU Accelerometer & Gyroscope

Supported on:RVC2RVC4
This example shows accelerometer and gyroscope at a combined/synchronized 400 Hz rate using the onboard IMU. Returns acceleration [m/s^2] and angular velocity [rad/s].

Demo

Example script output
Command Line
1~/examples/IMU$ python3 imu_gyroscope_accelerometer.py
2Accelerometer timestamp: 27 days, 4:31:26.532170
3Latency [ms]: 0:00:00.004806
4Accelerometer [m/s^2]: x: -0.098162 y: -0.062249 z: -9.715671
5Gyroscope timestamp: 27 days, 4:31:26.532170
6Gyroscope [rad/s]: x: 0.002131 y: 0.019175 z: 0.001065
7Accelerometer timestamp: 27 days, 4:31:26.534664
8Latency [ms]: 0:00:00.006309
9Accelerometer [m/s^2]: x: -0.064643 y: -0.119710 z: -9.758766
10Gyroscope timestamp: 27 days, 4:31:26.534664
11Gyroscope [rad/s]: x: 0.002131 y: 0.019175 z: 0.002131
This example requires the DepthAI v3 API, see installation instructions.

Pipeline

Source code

Python

Python
GitHub
1#!/usr/bin/env python3
2import depthai as dai
3
4
5def timeDeltaToMilliS(delta) -> float:
6    return delta.total_seconds()*1000
7
8
9# Create pipeline
10with dai.Pipeline() as pipeline:
11    # Define sources and outputs
12    imu = pipeline.create(dai.node.IMU)
13
14    # enable ACCELEROMETER_RAW at 500 hz rate
15    imu.enableIMUSensor(dai.IMUSensor.ACCELEROMETER_RAW, 480)
16    # enable GYROSCOPE_RAW at 400 hz rate
17    imu.enableIMUSensor(dai.IMUSensor.GYROSCOPE_RAW, 400)
18    # it's recommended to set both setBatchReportThreshold and setMaxBatchReports to 20 when integrating in a pipeline with a lot of input/output connections
19    # above this threshold packets will be sent in batch of X, if the host is not blocked and USB bandwidth is available
20    imu.setBatchReportThreshold(1)
21    # maximum number of IMU packets in a batch, if it's reached device will block sending until host can receive it
22    # if lower or equal to batchReportThreshold then the sending is always blocking on device
23    # useful to reduce device's CPU load  and number of lost packets, if CPU load is high on device side due to multiple nodes
24    imu.setMaxBatchReports(10)
25
26    imuQueue = imu.out.createOutputQueue(maxSize=50, blocking=False)
27
28    pipeline.start()
29    baseTs = None
30    while pipeline.isRunning():
31        try:
32            imuData = imuQueue.get()
33        except KeyboardInterrupt:
34            break
35        assert isinstance(imuData, dai.IMUData)
36        imuPackets = imuData.packets
37        for imuPacket in imuPackets:
38            acceleroValues = imuPacket.acceleroMeter
39            gyroValues = imuPacket.gyroscope
40
41            acceleroTs = acceleroValues.getTimestamp()
42            gyroTs = gyroValues.getTimestamp()
43
44            imuF = "{:.06f}"
45            tsF  = "{:.03f}"
46
47            print(f"Accelerometer timestamp: {acceleroTs}")
48            print(f"Latency [ms]: {dai.Clock.now() - acceleroValues.getTimestamp()}")
49            print(f"Accelerometer [m/s^2]: x: {imuF.format(acceleroValues.x)} y: {imuF.format(acceleroValues.y)} z: {imuF.format(acceleroValues.z)}")
50            print(f"Gyroscope timestamp: {gyroTs}")
51            print(f"Gyroscope [rad/s]: x: {imuF.format(gyroValues.x)} y: {imuF.format(gyroValues.y)} z: {imuF.format(gyroValues.z)} ")
52            print()

C++

1#include <atomic>
2#include <iomanip>
3#include <iostream>
4#include <memory>
5
6#include "depthai/depthai.hpp"
7
8// Helper function to convert time delta to milliseconds
9float timeDeltaToMilliS(const std::chrono::steady_clock::duration& delta) {
10    return std::chrono::duration_cast<std::chrono::milliseconds>(delta).count();
11}
12
13int main() {
14    // Create pipeline
15    dai::Pipeline pipeline;
16
17    // Define sources and outputs
18    auto imu = pipeline.create<dai::node::IMU>();
19
20    // Enable ACCELEROMETER_RAW at 480 hz rate
21    imu->enableIMUSensor(dai::IMUSensor::ACCELEROMETER_RAW, 480);
22    // Enable GYROSCOPE_RAW at 400 hz rate
23    imu->enableIMUSensor(dai::IMUSensor::GYROSCOPE_RAW, 400);
24
25    // Set batch report threshold and max batch reports
26    imu->setBatchReportThreshold(1);
27    imu->setMaxBatchReports(10);
28
29    // Create output queue
30    auto imuQueue = imu->out.createOutputQueue(50, false);
31
32    // Start pipeline
33    pipeline.start();
34    std::cout << "IMU pipeline started. Press Ctrl+C to stop." << std::endl;
35
36    // Set up output formatting
37    std::cout << std::fixed << std::setprecision(6);
38
39    while(pipeline.isRunning()) {
40        auto imuData = imuQueue->get<dai::IMUData>();
41        if(imuData == nullptr) continue;
42
43        for(const auto& imuPacket : imuData->packets) {
44            auto acceleroValues = imuPacket.acceleroMeter;
45            auto gyroValues = imuPacket.gyroscope;
46
47            auto acceleroTs = acceleroValues.getTimestamp();
48            auto gyroTs = gyroValues.getTimestamp();
49
50            // Print accelerometer data
51            std::cout << "Accelerometer timestamp: " << acceleroTs.time_since_epoch().count() << std::endl;
52            std::cout << "Latency [ms]: " << timeDeltaToMilliS(std::chrono::steady_clock::now() - acceleroValues.getTimestamp()) << std::endl;
53            std::cout << "Accelerometer [m/s^2]: x: " << acceleroValues.x << " y: " << acceleroValues.y << " z: " << acceleroValues.z << std::endl;
54
55            // Print gyroscope data
56            std::cout << "Gyroscope timestamp: " << gyroTs.time_since_epoch().count() << std::endl;
57            std::cout << "Gyroscope [rad/s]: x: " << gyroValues.x << " y: " << gyroValues.y << " z: " << gyroValues.z << std::endl;
58        }
59    }
60
61    // Cleanup
62    pipeline.stop();
63    pipeline.wait();
64
65    return 0;
66}

Need assistance?

Head over to Discussion Forum for technical support or any other questions you might have.