I found that information on someone's blog, but I can't find it now. Anyway, my code is below. I'm calling analogReference() in the setup() function of my program. As I said, if I remove it everything works fine (although I imagine my sensor calibrations are off). I tried placing analogReference() in the functions in the library right before I call analogRead(), but that didn't change the behavior at all.
The basic flow of the program is:
call init() which reads the sensor to get the starting angle
call getEuler() which calls getQ() which calls getValues(). getValues() uses analogRead().
My main program:
#include <FreeSixIMUanalog.h>
float angles[3];
int azpin=4; // imu analog input pins
int aypin=3;
int axpin=5;
int gxpin=0;
int gypin=1;
int gzpin=2;
FreeSixIMUanalog sixDOF = FreeSixIMUanalog(axpin,aypin,azpin,gxpin,gypin,gzpin);
void setup() {
// debug setup
Serial.begin(9600);
// set analog reference voltage to external voltage, which is hooked to 3.3V
analogReference(EXTERNAL);
delay(50);
sixDOF.init(100); //begin the IMU, read 100 samples
delay(5);
}
void loop() {
sixDOF.getEuler(angles);
Serial.print(angles[0]);
Serial.print(" | ");
Serial.print(angles[1]);
Serial.print(" | ");
Serial.print(angles[2]);
Serial.println(" | ");
delay(70);
}
The library header:
#include "Arduino.h"
#ifndef FreeSixIMUanalog_h
#define FreeSixIMUanalog_h
#define twoKpDef (2.0f * 0.5f) // 2 * proportional gain
#define twoKiDef (2.0f * 0.1f) // 2 * integral gain
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
class FreeSixIMUanalog
{
public:
FreeSixIMUanalog(int axpin, int aypin, int azpin, int gxpin, int gypin, int gzpin);
void init();
void init(int init_samples);
void getRawValues(int * raw_values);
void getValues(float * values);
void getQ(float * q);
void getEuler(float * angles);
void getYawPitchRoll(float * ypr);
void getAngles(float * angles);
int* raw_acc, raw_gyro, raw_magn;
private:
int _axpin, _aypin, _azpin, _gxpin, _gypin, _gzpin;
int _gx_zero, _gy_zero, _gz_zero;
void AHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz);
float iq0, iq1, iq2, iq3;
float exInt, eyInt, ezInt; // scaled integral error
volatile float twoKp; // 2 * proportional gain (Kp)
volatile float twoKi; // 2 * integral gain (Ki)
volatile float q0, q1, q2, q3; // quaternion of sensor frame relative to auxiliary frame
volatile float integralFBx, integralFBy, integralFBz;
unsigned long lastUpdate, now; // sample period expressed in milliseconds
float sampleFreq; // half the sample period expressed in seconds
int startLoopTime;
};
float invSqrt(float number);
#endif // FreeSixIMUanalog_h