Pitch code

Dependencies:   MMA8451Q mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "MMA8451Q.h"
00003 
00004 Serial pc(USBTX, USBRX);
00005 float pitch, roll;
00006 int enter, back;
00007 #if   defined (TARGET_KL25Z) || defined (TARGET_KL46Z)
00008   PinName const SDA = PTE25;
00009   PinName const SCL = PTE24;
00010 #elif defined (TARGET_KL05Z)
00011   PinName const SDA = PTB4;
00012   PinName const SCL = PTB3;
00013 #elif defined (TARGET_K20D50M)
00014   PinName const SDA = PTB1;
00015   PinName const SCL = PTB0;
00016 #else
00017   #error TARGET NOT DEFINED
00018 #endif
00019 
00020 #define MMA8451_I2C_ADDRESS (0x1d<<1)
00021 
00022 DigitalIn RIGHT(D8);
00023 DigitalIn LEFT(D9);
00024 
00025 void pc_listen() {
00026     if (pc.readable()) {
00027         char input = pc.getc();
00028         
00029         switch(input) {
00030             case '1': pc.printf("%1.2f,%1.2f, %d, %d\r\n", roll, pitch, enter, back);
00031             break;
00032         }    
00033     }
00034 }
00035 
00036 int main(void)
00037 {   
00038     float x=0, y=0, z=0;
00039     MMA8451Q acc(SDA, SCL, MMA8451_I2C_ADDRESS);
00040     PwmOut rled(LED1);
00041     PwmOut gled(LED2);
00042     PwmOut bled(LED3);
00043 
00044 //    printf("MMA8451 ID: %d\n", acc.getWhoAmI());
00045 
00046     while (true) {        
00047         x = acc.getAccX();
00048         y = acc.getAccY();
00049         z = acc.getAccZ();
00050         
00051         roll = 180*atan(x / sqrt(z*z + y*y))/3.1415;
00052         pitch = 180*atan(y / sqrt(x*x + z*z))/3.1415;
00053         
00054         rled = 1.0f - x;
00055         gled = 1.0f - y;
00056         bled = 1.0f - z;
00057         enter = !RIGHT.read();
00058         back = !LEFT.read();
00059             
00060 //        wait(0.1f);
00061         pc_listen();
00062 
00063     }
00064 }