book collections email follower instructable user

Step 5: Measuring Angle of Inclination (IMU)

Picture of Measuring Angle of Inclination (IMU)

Implementing the code for the BNO055 is quite simple, thanks to the libraries written by the programmers at Adafruit. We will be utilizing the Adafruit_BNO055 driver library as well as the Adafruit Unified Sensor library.

Let's begin by updating our header file to interact with the IMU.

#ifndef Monstro_h
#define Monstro_h

#include "Arduino.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

class Monstro {

  public:
    Monstro(int leftForward, int leftBackward, int leftSpeedPin,
        int rightForward, int rightBackward, int rightSpeedPin,
        int trigA, int echoA, int trigB, int echoB);

    // Behavior
    bool Update();
    void Initialize();

    // IMU
    volatile double xTilt;
    volatile double yTilt;
    volatile double zTilt;
    
  private:
     
    // IMU
    Adafruit_BNO055 _bno;
    void initializeIMU();
    void readIMU();

};
#endif


We have added a few things to our header file.

  • First off, you will notice three include statements, which ensure we have access to the Adafruit libraries as well as the imumaths.h library whose functions we will require when implementing the IMU reading.
  • We have also added public variables xTilt, yTilt, and zTilt. These are where we will be storing the data we retrieve from the IMU during each update cycle. Notice that we have marked them as volatile, this is because we will be using them in a timer interrupt later on in the tutorial.
  • We have also added a BNO055 object (_bno), an initializer function to set it up, and a reading function to use during the update cycle.

Now lets implement these functions in the source file:

#include "Arduino.h"
#include "monstro.h"

Monstro::Monstro(int leftForward, int leftBackward, int leftSpeedPin,
         int rightForward, int rightBackward, int rightSpeedPin,
         int trigA, int echoA, int trigB, int echoB)
{

}

// Behavior
void Monstro::Initialize() {
  initializeIMU();
}
bool Monstro::Update() {
  readIMU();
}

// IMU
void Monstro::initializeIMU() {
  _bno = Adafruit_BNO055(55);
  if (!_bno.begin())
  {
    Serial.print("No BNO055 detected");
    while (1);
  }
  delay(1000);
  _bno.setExtCrystalUse(true);
}
void Monstro::readIMU() {
  sensors_event_t event;
  _bno.getEvent(&event);

  xTilt = event.orientation.x;
  yTilt = event.orientation.y;
  zTilt = event.orientation.z;
}


We have now implemented our IMU functionalities:

  • We have included the IMU initialization inside of our master Initialize() function, and included the IMU reading inside of our master Update() function.
  • We have also implemented the code for IMU initialization, where we interface with the BNO055
  • And finally implemented the reading of our robots absolute orientation inside of our readIMU() function, which then assigns the three tilts to our internal variables.