-1

I have an Arduino Nano 33 IoT and I want to get the angle of it using the built-in gyro but I can't seem to find any example code that does this.

The default gyro and accelerometer example code doesn't help. Is it even possible to do this?

3
  • 2
    a gyro detects the rate of angular change, not an absolute angle ... an accelerometer can measure an angle with respect to gravity
    – jsotola
    Oct 31, 2020 at 22:39
  • I tried looking for both but there is no code that does it. Could you help me find it? Nov 1, 2020 at 15:44
  • 1
    All I can find is changing numbers but no angles. Nov 1, 2020 at 15:44

2 Answers 2

1

You wil have to calculate the angles. Some trigonometry is required, and for the gyroscopes, also some integration. You can read about it here, and in many other places.

You will get the best results if you combine the data from the gyroscopes and the accelerometers using a complementary filter, a Kalman filter, or an other algorithm. These are also easily googled.

There is some example code for the LSM6DS3 IMU on the Nano 33 IoT here on Github.

1
  • This is the best solution. This filter is a lot faster than the MadgwickAHRS! Amazing! Jan 15, 2021 at 15:35
2

You are supposed to use a filter library on top of the output of the gyro as well as the accelerometer data (both is used!) to get angles ... https://www.arduinolibraries.info/libraries/madgwick

Here is a working example that prints the pitch of the sensor from +90 to -90 degrees:

//#include <SPI.h>
//#include <Wire.h>  
#include <Arduino_LSM6DS3.h>
#include <MadgwickAHRS.h>
#include <Math.h>

float pitchFilteredOld;
Madgwick filter;
const float sensorRate = 104.00;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  if(!IMU.begin())  {
    Serial.println("Failed to initialize IMU!");
    while (1);
  }
  filter.begin(sensorRate);
  Serial.println("Setup complete!");
}  
void loop() {
  float xAcc, yAcc, zAcc;
  float xGyro, yGyro, zGyro;
  float roll, pitch, heading;
  if(IMU.accelerationAvailable() && IMU.gyroscopeAvailable()){
    IMU.readAcceleration(xAcc, yAcc, zAcc);
    IMU.readGyroscope(xGyro, yGyro, zGyro); 
    filter.updateIMU(xGyro, yGyro, zGyro, xAcc, yAcc, zAcc);
    pitch = filter.getPitch();
    float pitchFiltered = 0.1 * pitch + 0.9 * pitchFilteredOld; // low pass filter
    Serial.println("pitch: " + String(pitchFiltered));
    pitchFilteredOld = pitchFiltered;
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.