Playing around with accelerometer and magnetometer on mbed KL46Z

Dependencies:   MAG3110 MMA8451Q PinDetect mbed TSI

main.cpp

Committer:
mohammmo
Date:
2014-02-03
Revision:
2:bb31f097af0f
Parent:
0:648dde0c4ef8
Child:
3:552b7c450b2f
Child:
5:4ccda4b4f345

File content as of revision 2:bb31f097af0f:

#include "mbed.h"
#include "PinDetect.h"
#include "MMA8451Q.h"
#include "MAG3110.h"
#include "TSISensor.h"

#define MMA8451_I2C_ADDRESS (0x1d<<1)

// Declare output LEDs
DigitalOut ledgreen(PTD5);
DigitalOut ledred(PTE29);

// Declare USB serial connection
Serial pc(USBTX,USBRX);

// Declare timer interrupt
Ticker timerAcc;
Ticker timerMag;
Ticker timerLight; 
Ticker timerTouch;

// Declare pointer variables
float xAcc;
float yAcc;
float zAcc;
int xMag;
int yMag;
int zMag;
float xLight; 
float xTouch; 

// Declare Accelerometer pins and I2C address
MMA8451Q acc(PTE25, PTE24, MMA8451_I2C_ADDRESS, 0, 0);
// Declare Magnetometer pins
MAG3110 mag(PTE25, PTE24);
// Declare touch sensor pin
TSISensor touch;
// Declare light sensor pin
AnalogIn light(PTE22);

// Functions
void init();
void accTime();
void magTime();
void lightTime();
void touchTime();

void init()
{
    // Attach timerAcc
    timerAcc.attach(&accTime, 0.5);
    timerMag.attach(&magTime, 0.75);
    timerLight.attach(&lightTime, 0.5);
    timerTouch.attach(&touchTime, 0.5);
    ledred = 0; 
    ledgreen = 0;   
}

int main() 
{
    // Initialize
    init();

    while(1)
    {
        // Read and print data from accelerometer
        pc.puts("Accelerometer: ");
        pc.printf("X: %f, Y: %f, Z: %f\t", xAcc, yAcc, zAcc);
        // Read data from magnetometer
        pc.puts("Magnetometer: ");
        pc.printf("X: %d, Y: %d, Z: %d\t", xMag, yMag, zMag);
        pc.puts("Light: ");
        pc.printf(" %f\t", xLight);
        pc.puts("touch: ");
        pc.printf(" %f\r\n", xTouch);
        wait(0.5);
    }
}

void accTime() 
{
    xAcc = abs(acc.getAccX());
    yAcc = abs(acc.getAccY());
    zAcc = abs(acc.getAccZ());
    ledgreen = !ledgreen;
}

void magTime()
{
    xMag = mag.getXVal();
    yMag = mag.getYVal();
    zMag = mag.getZVal();
    ledred = !ledred;
}

void lightTime()
{
    xLight = 1 - light.read();
}

void touchTime()
{
    xTouch = 1 - touch.readPercentage();
}