Thomas Allen / Mbed 2 deprecated AccelerometerTest1611

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 //AccelerometerTest
00002 //Toby Galal
00003 //6 November 2015
00004 //A program used to gather data from ADXL335 accelerometers and print them to file (.txt) in a MatLab-compliant format
00005 
00006 #include "mbed.h"
00007 
00008 //Hardware Initialisation
00009 AnalogIn XIn(p15); //X Input
00010 AnalogIn YIn(p16); //Y Input
00011 AnalogIn ZIn(p17); //Z Input
00012 Serial pc(USBTX, USBRX); //Serial to print readings to terminal
00013 Ticker timer; //Timer to call ISR
00014 
00015 //Global Variables
00016 float X, Y, Z; //variables to store XYZ readings
00017 float Xo, Yo, Zo; //variables to store 0G bias readings
00018 int flag; //flag for ISR
00019 float CalX[1000], CalY[1000], CalZ[1000]; //arrays to store calibration readings
00020 int n = 0; //variable to store the number of readings
00021 
00022 //Function Prototypes
00023 void Calibrate();
00024 void Send_Data();
00025 void ISR();
00026 
00027 
00028 //Main Function    
00029 int main() {
00030     
00031     wait(2.0); //allow accelerometer to stabilise
00032     timer.attach(&Calibrate, 0.001); //attach Calibrate function to timer
00033 
00034     while (1) {
00035         if (flag) { //if flag has been set
00036             flag = 0; //reset flag
00037             Send_Data();
00038         }
00039     }
00040 }
00041 
00042 //Function Definitions
00043 void Calibrate() {        
00044     CalX[n] = XIn.read() * 3.3; //read XYZ pins and store in array
00045     CalY[n] = YIn.read() * 3.3;
00046     CalZ[n] = ZIn.read() * 3.3;
00047     n++; //increment counter
00048     
00049     if (n == 1000) { //when enough samples have been taken
00050         timer.detach(); //detach timer from Calibrate()
00051         
00052         for (int i = 0; i < 1000; i++) { //sum sample readings
00053             Xo = Xo + CalX[i];
00054             Yo = Yo + CalY[i];
00055             Zo = Zo + CalZ[i];
00056         }
00057 
00058         Xo = Xo / 1000; //find mean and store it
00059         Yo = Yo / 1000;
00060         Zo = Zo / 1000;
00061         
00062         pc.printf("Calibration Values = %.3f | %.3f | %.3f\n\r", Xo, Yo, Zo); //debug
00063         timer.attach(&ISR, 0.001); //attach timer to ISR for real data collection
00064     }
00065 }
00066 
00067 void Send_Data() {
00068     X = ((XIn.read() * 3.3) - Xo) / 0.3; //read input, subtract zeroed value to find offset, and convert to g (300mv/g)
00069     Y = ((YIn.read() * 3.3) - Yo) / 0.3;
00070     Z = ((ZIn.read() * 3.3) - Zo) / 0.3;   
00071     pc.printf("%.3f %.3f %.3f",X, Y, Z); //print output to serial
00072 }
00073 
00074 void ISR() {
00075     flag = 1; //set flag
00076 }