Main Content

Calculate Pitch and Roll on Arduino Using IMU Sensor

This example shows how to read the acceleration and angular velocity data from IMU sensor mounted on Arduino® hardware and calculate the pitch and roll angles.

Hardware Required

  • Arduino (any Arduino hardware with I2C peripheral that supports code generation from MATLAB Function block)

  • MPU9250 (any IMU sensor with accelerometer and gyroscope)

Note: Any IMU sensor that supports code generation from MATLAB function block can be used in this example. If any other sensor is used to create IMU sensor object, for example if LSM9DS1 sensor is used, then the object creation needs to be modified to lsm9ds1(a) from mpu9250(a).

Model

Simulink Support Package for Arduino hardware provides a pre-configured model that you can use to read the acceleration and angular velocity data from IMU sensor mounted on Arduino hardware and calculate the pitch and roll angles.

Open the arduino_imu_pitch_roll_calculation Simulink model.

Algorithm

The alignment of the sensor axes should be as following:

  • X-axis = Longitudinal axis or roll axis

  • Y-axis = Transverse axis or pitch axis

  • Z-axis = Vertical axis or yaw axis

In this model pitch and roll angle is calculated using accelerometer and gyroscope readings. After deploying the model on hardware, you can find out the pitch and roll angle based on the orientation of the sensor. The range of pitch and roll angle is [-90 degree, 90 degree]. If the sensor is kept steady and parallel to ground, for example z-axis perpendicular to ground, both the readings should be 0. The pitch angle is positive for counterclockwise rotation with respect to Pitch axis and negative for clockwise rotation. For roll angle it is the same. To filter out noise at the beginning of the execution of the program, when the sensor is kept steady on ground with Z-axis being perpendicular to ground, the sensor is read multiple times and offset values for pitch and roll angle are calculated. These values are subtracted later when pitch and roll angle is calculated at every step. This removes steady noise from sensor readings to some extent.

Configure and Run the Model on Arduino Board

  1. Open the arduino_imu_pitch_roll_calculation Simulink model.

  2. On the Hardware tab, click Hardware Settings to open the Configuration Parameters dialog box.

  3. Select the Hardware Implementation pane and select your Arduino hardware from the Hardware board parameter list. Do not change any other settings. Click OK.

  4. On the Hardware tab of the Simulink model, in the Mode section, select Run on board and then click Build, Deploy & Start to run this model on the Arduino board.

  5. To view the output in MATLAB, run the model using the Monitor and Tune feature. To do this, on the Hardware tab of the Simulink model, in the Mode section, select Run on board and then click Monitor & Tune.