Playing around with accelerometer and magnetometer on mbed KL46Z

Dependencies:   MAG3110 MMA8451Q PinDetect mbed TSI

Revision:
7:1cd1e239acf0
Parent:
5:4ccda4b4f345
--- a/main.cpp	Mon Feb 03 05:38:17 2014 +0000
+++ b/main.cpp	Tue Feb 04 02:23:48 2014 +0000
@@ -3,6 +3,7 @@
 #include "MMA8451Q.h"
 #include "MAG3110.h"
 #include "TSISensor.h"
+#include <string>
 
 #define MMA8451_I2C_ADDRESS (0x1d<<1)
 
@@ -19,6 +20,9 @@
 Ticker timerLight; 
 Ticker timerTouch;
 
+//Sampling rate
+float sample = 0.5;
+
 // Declare pointer variables
 float xAcc;
 float yAcc;
@@ -37,6 +41,11 @@
 TSISensor touch;
 // Declare light sensor pin
 AnalogIn light(PTE22);
+// variables for receive interrupt  
+const int buffer_size = 255;
+char rx_buffer[buffer_size];
+int track_rx = 0;
+bool received = false; 
 
 // Functions
 void init();
@@ -44,14 +53,17 @@
 void magTime();
 void lightTime();
 void touchTime();
+void receive_handler();
+void change_interval(float sample);
 
 void init()
 {
     // Attach timerAcc
-    timerAcc.attach(&accTime, 0.05);
-    timerMag.attach(&magTime, 0.05);
-    timerLight.attach(&lightTime, 0.05);
-    timerTouch.attach(&touchTime, 0.05);
+    timerAcc.attach(&accTime, sample);
+    timerMag.attach(&magTime, sample);
+    timerLight.attach(&lightTime, sample);
+    timerTouch.attach(&touchTime, sample);
+    pc.attach(&receive_handler,Serial::RxIrq);
     ledred = 0; 
     ledgreen = 0;   
 }
@@ -64,8 +76,16 @@
     while(1)
     {
         // read all sensor data 
-        pc.printf("%f %f %f %d %d %d %f %f\n", xAcc, yAcc, zAcc, xMag, yMag, zMag, xLight, xTouch);
-        wait(0.05);
+        //pc.printf("%f %f %f %d %d %d %f %f\n", xAcc, yAcc, zAcc, xMag, yMag, zMag, xLight, xTouch);
+        //wait(0.05);
+        if (received){
+            __disable_irq();    
+            sscanf(rx_buffer,"%f",&sample);
+            pc.printf("%f\r\n", sample);
+            change_interval(sample);
+            received = false; 
+            __enable_irq();     
+        }
     }
 }
 
@@ -93,4 +113,30 @@
 void touchTime()
 {
     xTouch = 1 - touch.readPercentage();
-}
\ No newline at end of file
+}
+
+void receive_handler(){
+    while (pc.readable() && track_rx < buffer_size){
+        rx_buffer[track_rx] = pc.getc();
+        if (rx_buffer[track_rx] == '#'){
+            rx_buffer[track_rx] = '\0';
+            track_rx=0;
+            received = true; 
+            break;
+        }
+        track_rx++;
+    }
+    return;
+}
+
+void change_interval(float sample)
+{
+    timerAcc.detach();
+    timerMag.detach();
+    timerLight.detach();
+    timerTouch.detach();
+    timerAcc.attach(&accTime, sample);
+    timerMag.attach(&magTime, sample);
+    timerLight.attach(&lightTime, sample);
+    timerTouch.attach(&touchTime, sample);
+} 
\ No newline at end of file