11/16

Dependencies:   mbed

main.cpp

Committer:
el13ytg
Date:
2015-11-08
Revision:
0:0dc99d71b2f3
Child:
1:e41af8c958b8

File content as of revision 0:0dc99d71b2f3:

//AccelerometerTest
//Toby Galal
//6 November 2015
//A program used to gather data from ADXL335 accelerometers and print them to file (.txt) in a MatLab-compliant format

#include "mbed.h"

//Hardware Initialisation
AnalogIn XIn(p15); //X Input
AnalogIn YIn(p16); //Y Input
AnalogIn ZIn(p17); //Z Input
//Serial pc(USBTX, USBRX); //Serial to print readings to terminal
Ticker timer; //Timer to call ISR
LocalFileSystem local("local"); // create local filesystem
BusOut leds(LED4,LED3,LED2,LED1); //debug

//Global Variables
float XOut, YOut, ZOut; //variables to store XYZ readings
float CalX, CalY, CalZ; //variables to store 0G bias readings
int flag; //flag for ISR
float X[1000], Y[1000], Z[1000]; //arrays to store results
int n; //variable to store the number of readings

//Function Prototypes
void Calibrate();
void ISR();
void Send_Data();
void writeDataToFile();

//Main Function    
int main() {
    
    wait(2.0); //allow accelerometer to stabilise
    Calibrate();
    timer.attach(&ISR, 0.1); //attach ISR function to timer
    
    while (n < 1000) {
        if (flag) { //if flag has been set
            flag = 0; //reset flag
            Send_Data();
        }
    }
    writeDataToFile();
}

//Function Definitions
void Calibrate() {
    CalX = XIn.read() * 3.3; //static values
    CalY = YIn.read() * 3.3;
    CalZ = ZIn.read() * 3.3;
}

void ISR() {
    flag = 1;
}

void Send_Data() {
    XOut = (XIn.read() * 3.3) - CalX; //differences
    YOut = (YIn.read() * 3.3) - CalY;
    ZOut = (ZIn.read() * 3.3) - CalZ;
    X[n] = XOut; //store result in array
    Y[n] = YOut;
    Z[n] = ZOut;
    n++;
        
   //pc.printf("%d) X = %.2f | Y = %.2f | Z = %.2f\n\r", n, XOut, YOut, ZOut);
}

void writeDataToFile() {
 
    leds = 15; // turn on LEDs for feedback
    FILE *results = fopen("/local/results.txt", "w"); // open 'results.txt' for writing
   
    fprintf(results, "x = ["); //print X array
    
    for (int i = 0; i < 999; i++) {
        fprintf(results, "%.2f,", X[i]);
    }
    
    fprintf(results, "%.2f]\n\r", X[999]);
    
    fprintf(results, "y = ["); //print Y array
    
    for (int i = 0; i < 999; i++) {
        fprintf(results, "%.2f,", Y[i]);
    }
    
    fprintf(results, "%.2f]\n\r", Y[999]);
    
    fprintf(results, "z = ["); //print Z array
    
    for (int i = 0; i < 999; i++) {
        fprintf(results, "%.2f,", Z[i]);
    }
    
    fprintf(results, "%.2f]\n\r", Z[999]);
     
    fclose(results); // close file
    leds = 0; // turn off LEDs to signify file access has finished
}