Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869#include "imu.h"#include "orientation.h"
#include <Arduino.h>
namespace {i2c_master_dev_handle_t device = nullptr;orientation::Filter filter;unsigned rotation = 0;uint32_t last_poll = 0;
bool read_reg(uint8_t reg, uint8_t *data, size_t size) { return i2c_master_transmit_receive(device, ®, 1, data, size, 10) == ESP_OK;}bool write_reg(uint8_t reg, uint8_t value) { uint8_t data[] = {reg, value}; return i2c_master_transmit(device, data, sizeof(data), 10) == ESP_OK;}}
bool imu_init(i2c_master_bus_handle_t bus) { // QMI8658 WHO_AM_I = 0x05. Probe both SA0 addresses; do not reset the // expander/shared bus or enable the unused gyroscope. for (uint8_t address : {0x6a, 0x6b}) { i2c_device_config_t config = {}; config.dev_addr_length = I2C_ADDR_BIT_LEN_7; config.device_address = address; config.scl_speed_hz = 100000; if (i2c_master_bus_add_device(bus, &config, &device) != ESP_OK) continue; uint8_t id = 0; if (read_reg(0x00, &id, 1) && id == 0x05 && write_reg(0x08, 0x00) && // CTRL7: disable while configuring write_reg(0x02, 0x40) && // CTRL1: address auto-increment write_reg(0x03, 0x06) && // CTRL2: +/-2g, 125 Hz write_reg(0x08, 0x01)) { // CTRL7: accel only Serial.printf("IMU QMI8658 ready address=0x%02x\n", address); return true; } i2c_master_bus_rm_device(device); device = nullptr; } Serial.println("IMU unavailable; keeping portrait"); return false;}
unsigned imu_rotation() { uint32_t now = millis(); if (!device || static_cast<uint32_t>(now - last_poll) < 50) return rotation; last_poll = now; uint8_t raw[6]; if (!read_reg(0x35, raw, sizeof(raw))) return rotation; float axes[3]; for (int i = 0; i < 3; ++i) { int16_t value = static_cast<int16_t>(static_cast<uint16_t>(raw[2*i]) | (static_cast<uint16_t>(raw[2*i+1]) << 8)); axes[i] = value / 16384.0f; } // The QMI8658 is mounted a quarter-turn from the panel: screen-right // is raw -Y, screen-down is raw +X. Using raw X/Y directly put the top // of the text on the left in every pose (physical-device test). unsigned next = filter.update(-axes[1], axes[0], axes[2], now); if (next != rotation) { rotation = next; Serial.printf("IMU rotation=%u accel=%.2f,%.2f,%.2f\n", rotation * 90, axes[0], axes[1], axes[2]); } return rotation;}