Advertisement
Guest User

mpuclass

a guest
Aug 1st, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <array>
  3. #include "MPU9250.h"
  4. #include <Adafruit_Sensor.h>
  5. #include <Adafruit_BNO055.h>
  6. #include <utility/imumaths.h>
  7. //#include <driver/adc.h>
  8. #include <Madgwick.h>
  9. #include <TaskScheduler.h>
  10.  
  11.  
  12.  
  13. class euler {
  14.     // maybe be more verbose
  15.     using axisvals = std::array<float, 3>;
  16.  
  17. private:
  18.     // apply constness to save RAM memory
  19.    // const std::array<float, 2> mag_field_strength =  {{ 41.85F, 40.6F }};
  20.    MPU9250 mpu;
  21.    Madgwick filter;
  22.    const std::array<float, 3> mag_offsets;
  23.    const std::array<std::array<float, 3> , 3> mag_softiron_matrix;
  24.    const std::array<float, 3> gyro_offsets{};
  25.  
  26. public:
  27.    euler(int gpio, const std::array<float, 3>& mag_offsets, const std::array<std::array<float, 3> , 3>& mag_softiron_matrix) :
  28.       mpu(SPI, gpio),
  29.       mag_offsets{mag_offsets},
  30.       mag_softiron_matrix{mag_softiron_matrix} {
  31.    }
  32.  
  33.    void setup() {
  34.      // do some setuping stuff
  35.      filter.begin(250);
  36.      mpu.setAccelRange(MPU9250::ACCEL_RANGE_2G);
  37.      mpu.setGyroRange(MPU9250::GYRO_RANGE_250DPS);
  38.      mpu.calibrateAccel();
  39.      mpu.calibrateGyro();
  40.   }
  41.  
  42.    axisvals calculate_stuff() {
  43.       mpu.readSensor();
  44.       // use const as much as possible
  45.       const std::array<float, 3> accel = {
  46.          mpu.getAccelX_mss(),
  47.          mpu.getAccelY_mss(),
  48.          mpu.getAccelZ_mss(),
  49.       };
  50.       const std::array<float, 3> gyro = {
  51.          mpu.getGyroX_rads(),
  52.          mpu.getGyroY_rads(),
  53.          mpu.getGyroZ_rads(),
  54.       };
  55.       const std::array<float, 3> magneto = {
  56.          mpu.getMagX_uT(),
  57.          mpu.getMagY_uT(),
  58.          mpu.getMagZ_uT(),
  59.       };
  60.       filter.update(gyro[0], gyro[1], gyro[2], accel[0], accel[1], accel[2], magneto[0], magneto[1], magneto[2]);
  61.       return {filter.getRoll(), filter.getPitch(),  filter.getYaw()};
  62.    }
  63. };
  64. euler mup(21, {10.44, 34.76, -49.86}, {{ 0.994, -0.023, -0.008 },{ -0.023, 1.027, 0.013 },{ -0.008, 0.013, 0.980 }});
  65.  
  66. void setup() {
  67.    for (auto&& imu : imus) {
  68.       imu.setup();
  69.    }
  70. }
  71.  
  72. void loop() {
  73.    for (auto&& imu : imus) {
  74.        const auto&vals =  imu.calculate_stuff();
  75.        for (auto&& v : vals) {
  76.            Serial.print(v);
  77.        }
  78.    }
  79. }
  80.  
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement