|
| 1 | +#include <CurieIMU.h> |
| 2 | +#include <MadgwickAHRS.h> |
| 3 | + |
| 4 | +Madgwick filter; |
| 5 | +unsigned long microsPerReading, microsPrevious; |
| 6 | +float accelScale, gyroScale; |
| 7 | + |
| 8 | +void setup() { |
| 9 | + Serial.begin(9600); |
| 10 | + |
| 11 | + // start the IMU and filter |
| 12 | + CurieIMU.begin(); |
| 13 | + CurieIMU.setGyroRate(25); |
| 14 | + CurieIMU.setAccelerometerRate(25); |
| 15 | + filter.begin(25); |
| 16 | + |
| 17 | + // Set the accelerometer range to 2G |
| 18 | + CurieIMU.setAccelerometerRange(2); |
| 19 | + // Set the gyroscope range to 250 degrees/second |
| 20 | + CurieIMU.setGyroRange(250); |
| 21 | + |
| 22 | + // initialize variables to pace updates to correct rate |
| 23 | + microsPerReading = 1000000 / 25; |
| 24 | + microsPrevious = micros(); |
| 25 | +} |
| 26 | + |
| 27 | +void loop() { |
| 28 | + int aix, aiy, aiz; |
| 29 | + int gix, giy, giz; |
| 30 | + float ax, ay, az; |
| 31 | + float gx, gy, gz; |
| 32 | + float roll, pitch, heading; |
| 33 | + unsigned long microsNow; |
| 34 | + |
| 35 | + // check if it's time to read data and update the filter |
| 36 | + microsNow = micros(); |
| 37 | + if (microsNow - microsPrevious >= microsPerReading) { |
| 38 | + |
| 39 | + // read raw data from CurieIMU |
| 40 | + CurieIMU.readMotionSensor(aix, aiy, aiz, gix, giy, giz); |
| 41 | + |
| 42 | + // convert from raw data to gravity and degrees/second units |
| 43 | + ax = convertRawAcceleration(aix); |
| 44 | + ay = convertRawAcceleration(aiy); |
| 45 | + az = convertRawAcceleration(aiz); |
| 46 | + gx = convertRawGyro(gix); |
| 47 | + gy = convertRawGyro(giy); |
| 48 | + gz = convertRawGyro(giz); |
| 49 | + |
| 50 | + // update the filter, which computes orientation |
| 51 | + filter.updateIMU(gx, gy, gz, ax, ay, az); |
| 52 | + |
| 53 | + // print the heading, pitch and roll |
| 54 | + roll = filter.getRoll(); |
| 55 | + pitch = filter.getPitch(); |
| 56 | + heading = filter.getYaw(); |
| 57 | + Serial.print("Orientation: "); |
| 58 | + Serial.print(heading); |
| 59 | + Serial.print(" "); |
| 60 | + Serial.print(pitch); |
| 61 | + Serial.print(" "); |
| 62 | + Serial.println(roll); |
| 63 | + |
| 64 | + // increment previous time, so we keep proper pace |
| 65 | + microsPrevious = microsPrevious + microsPerReading; |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +float convertRawAcceleration(int aRaw) { |
| 70 | + // since we are using 2G range |
| 71 | + // -2g maps to a raw value of -32768 |
| 72 | + // +2g maps to a raw value of 32767 |
| 73 | + |
| 74 | + float a = (aRaw * 2.0) / 32768.0; |
| 75 | + return a; |
| 76 | +} |
| 77 | + |
| 78 | +float convertRawGyro(int gRaw) { |
| 79 | + // since we are using 250 degrees/seconds range |
| 80 | + // -250 maps to a raw value of -32768 |
| 81 | + // +250 maps to a raw value of 32767 |
| 82 | + |
| 83 | + float g = (gRaw * 250.0) / 32768.0; |
| 84 | + return g; |
| 85 | +} |
0 commit comments