An mbed health monitor

Dependencies:   4DGL-uLCD-SE GP-20U7 PinDetect RPCInterface mbed

Files at this revision

API Documentation at this revision

Comitter:
dnergui3
Date:
Thu Dec 15 07:49:32 2016 +0000
Parent:
0:0de3867984e5
Commit message:
2nd commit

Changed in this revision

GPSstuff.lib Show annotated file Show diff for this revision Revisions of this file
LSM9DS1_Library_cal.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 0de3867984e5 -r ad5378dcef79 GPSstuff.lib
--- a/GPSstuff.lib	Sun Dec 11 22:58:51 2016 +0000
+++ b/GPSstuff.lib	Thu Dec 15 07:49:32 2016 +0000
@@ -1,1 +1,1 @@
-https://developer.mbed.org/users/dnergui3/code/GPSstuff/#1d9ff2a143da
+https://developer.mbed.org/users/dnergui3/code/GPSstuff/#bbad4e183649
diff -r 0de3867984e5 -r ad5378dcef79 LSM9DS1_Library_cal.lib
--- a/LSM9DS1_Library_cal.lib	Sun Dec 11 22:58:51 2016 +0000
+++ b/LSM9DS1_Library_cal.lib	Thu Dec 15 07:49:32 2016 +0000
@@ -1,1 +1,1 @@
-https://developer.mbed.org/users/dnergui3/code/LSM9DS1_Library_cal/#03be016abe03
+https://developer.mbed.org/users/dnergui3/code/LSM9DS1_Library_cal/#84a5a60b428b
diff -r 0de3867984e5 -r ad5378dcef79 main.cpp
--- a/main.cpp	Sun Dec 11 22:58:51 2016 +0000
+++ b/main.cpp	Thu Dec 15 07:49:32 2016 +0000
@@ -1,48 +1,382 @@
+// ESP8266 Static page WEB server to control Mbed
+
 #include "mbed.h"
 #include "LSM9DS1.h"
 #include "GPS.h"
 #include "GPSstuff.h"
-#include <time.h>
-#include <stdio.h> 
+#include <string>
+#include <iostream>
 
 Serial pc(USBTX, USBRX);
+Serial esp(p28, p27); // tx, rx
 GPS gps(p13, p14);
 GPSstuff object;
 LSM9DS1 IMU(p9, p10, 0xD6, 0x3C);
 
+char ssid[32] = "AndroidAP";     // enter WiFi router ssid inside the quotes
+char pwd [32] = "91d4f66f56c1"; // enter WiFi router passusrname inside the quotes
+
+char Steps[10];
+char Distance_travel[10];
+char Calories_burned[10];
+
 float a, ax, ay, az; //acceleration
-int steps=0, i=0, step_num;
+int i=0, n=0;
 bool flag=0;
     
-double buffer[4], speed, dist_travel=0, distance, totalDistance=0, threshold=1.1, time_elapsed=0;
+float buffer[4], d, totalDistance=0, threshold=1.1, calories=0, steps=0;
+
+// things for sending/receiving data over serial
+volatile int tx_in=0;
+volatile int tx_out=0;
+volatile int rx_in=0;
+volatile int rx_out=0;
+const int buffer_size = 4095;
+char tx_buffer[buffer_size+1];
+char rx_buffer[buffer_size+1];
+void Tx_interrupt();
+void Rx_interrupt();
+void send_line();
+void read_line();
+
+int DataRX;
+int update;
+int count;
+char cmdbuff[1024];
+char replybuff[4096];
+char webdata[4096]; // This may need to be bigger depending on WEB browser used
+char webbuff[4096];     // Currently using 1986 characters, Increase this if more web page data added
+char timebuf[30];
+void SendCMD(),getreply(),ReadWebData(),startserver();
+void gettime(),setRTC(), getsteps(), getdistance();
+char rx_line[1024];
+int port        =80;  // set server port
+int SERVtimeout =5;    // set server timeout in seconds in case link breaks.
+struct tm t;
+// manual set RTC values
+int minute      =00;    // 0-59
+int hour        =12;    // 2-23
+int dayofmonth  =26;    // 1-31
+int month       =8;     // 1-12
+int year        =15;    // last 2 digits
+
+int main()
+{
+    pc.baud(9600);
+    esp.baud(9600);
+    // Setup a serial interrupt function to receive data
+    esp.attach(&Rx_interrupt, Serial::RxIrq);
+    // Setup a serial interrupt function to transmit data
+    esp.attach(&Tx_interrupt, Serial::TxIrq);
+    if (time(NULL) < 1420070400) {
+        setRTC();
+    }
+    startserver();
+    DataRX=0;
+    ReadWebData();
+    IMU.begin();
+    if (!IMU.begin()) {
+        pc.printf("Failed to communicate with LSM9DS1.\n");
+    }
+    IMU.calibrate(1);
+    while(1) {
+        while(n<26){
+            getsteps();
+            wait(0.2);
+            n++;
+        }
+        //if(DataRX==1) {
+        ReadWebData();
+        esp.attach(&Rx_interrupt, Serial::RxIrq);
+        // get new values
+        gettime();
+        getdistance();
+        // send new values
+        sprintf(cmdbuff, "count,time,steps,distance,calories=%d,\"%s\",\"%s\",\"%s\",\"%s\"\r\n",count,timebuf,Steps,Distance_travel, Calories_burned);
+//                sprintf(cmdbuff, "count,time,steps,distance= %d,\"%s\",\"%s\",\"%s\"\r\n",count,timebuf,Steps,Distance_travel);
+        SendCMD();
+        getreply(); 
+        n=0; 
+    }
+}
+
+// Reads and processes GET and POST web data
+void ReadWebData()
+{
+    wait_ms(200);
+    esp.attach(NULL,Serial::RxIrq);
+    DataRX=0;
+    memset(webdata, '\0', sizeof(webdata));
+    strcpy(webdata, rx_buffer);
+    memset(rx_buffer, '\0', sizeof(rx_buffer));
+    rx_in = 0;
+    rx_out = 0;
+    // check web data for form information
+    if( strstr(webdata, "POST") != NULL ) { // set update flag if POST request
+        update=1;
+    }
+    if( strstr(webdata, "GET") != NULL && strstr(webdata, "favicon") == NULL ) { // set update flag for GET request but do not want to update for favicon requests
+        update=1;
+    }
+}
+// Starts webserver
+void startserver()
+{
+    gettime();
+    getsteps();
+    getdistance();
+    pc.printf("++++++++++ Resetting ESP ++++++++++\r\n");
+    strcpy(cmdbuff,"node.restart()\r\n");
+    SendCMD();
+    wait(2);
+    getreply();
+    
+    pc.printf("\n++++++++++ Starting Server ++++++++++\r\n> ");
+
+    // initial values
+    sprintf(cmdbuff, "count,time,steps,distance,calories=%d,\"%s\",\"%s\",\"%s\",\"%s\"\r\n",count,timebuf,Steps,Distance_travel, Calories_burned);
+    SendCMD();
+    getreply();
+    wait(0.5);
 
-int getsteps(){
+    //create server
+    sprintf(cmdbuff, "srv=net.createServer(net.TCP,%d)\r\n",SERVtimeout);
+    SendCMD();
+    getreply();
+    wait(0.5);
+    strcpy(cmdbuff,"srv:listen(80,function(conn)\r\n");
+    SendCMD();
+    getreply();
+    wait(0.3);
+        strcpy(cmdbuff,"conn:on(\"receive\",function(conn,payload) \r\n");
+        SendCMD();
+        getreply();
+        wait(0.3);
+        
+        //print data to mbed
+        strcpy(cmdbuff,"print(payload)\r\n");
+        SendCMD();
+        getreply();
+        wait(0.2);
+       
+        //web page data
+        strcpy(cmdbuff,"conn:send('<!DOCTYPE html><html><body><h1>Mbed IoT Web Controller</h1>')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.4);
+        strcpy(cmdbuff,"conn:send('<br>Last hit (based on mbed RTC time): '..time..'<br><hr>')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.4);
+        strcpy(cmdbuff,"conn:send('Steps: '..steps..' <br>Distance: '..distance..' km<br><hr>')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.3);
+        strcpy(cmdbuff,"conn:send('Calories: '..calories..' kcal<br><hr>')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.3);
+        strcpy(cmdbuff,"conn:send('<form method=\"POST\"')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.3);
+        strcpy(cmdbuff,"conn:send('<p><input type=\"submit\" value=\"Update\"></form>')\r\n");
+        SendCMD();
+        getreply();
+        wait(0.3);
+        // end web page data
+        strcpy(cmdbuff, "conn:on(\"sent\",function(conn) conn:close() end)\r\n"); // close current connection
+        SendCMD();
+        getreply();
+        wait(0.3);
+        strcpy(cmdbuff, "end)\r\n");
+        SendCMD();
+        getreply();
+        wait(0.2);
+    strcpy(cmdbuff, "end)\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+
+    strcpy(cmdbuff, "tmr.alarm(0, 1000, 1, function()\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff, "if wifi.sta.getip() == nil then\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff, "print(\"Connecting to AP...\\n\")\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff, "else\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff, "ip, nm, gw=wifi.sta.getip()\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff,"print(\"IP Address: \",ip)\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff,"tmr.stop(0)\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff,"end\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    strcpy(cmdbuff,"end)\r\n");
+    SendCMD();
+    getreply();
+    wait(0.2);
+    
+    pc.printf("\n\n++++++++++ Ready ++++++++++\r\n\n");
+}
+
+
+// ESP Command data send
+void SendCMD()
+{
+    int i;
+    char temp_char;
+    bool empty;
+    i = 0;
+// Start Critical Section - don't interrupt while changing global buffer variables
+    NVIC_DisableIRQ(UART1_IRQn);
+    empty = (tx_in == tx_out);
+    while ((i==0) || (cmdbuff[i-1] != '\n')) {
+// Wait if buffer full
+        if (((tx_in + 1) % buffer_size) == tx_out) {
+// End Critical Section - need to let interrupt routine empty buffer by sending
+            NVIC_EnableIRQ(UART1_IRQn);
+            while (((tx_in + 1) % buffer_size) == tx_out) {
+            }
+// Start Critical Section - don't interrupt while changing global buffer variables
+            NVIC_DisableIRQ(UART1_IRQn);
+        }
+        tx_buffer[tx_in] = cmdbuff[i];
+        i++;
+        tx_in = (tx_in + 1) % buffer_size;
+    }
+    if (esp.writeable() && (empty)) {
+        temp_char = tx_buffer[tx_out];
+        tx_out = (tx_out + 1) % buffer_size;
+// Send first character to start tx interrupts, if stopped
+        esp.putc(temp_char);
+    }
+// End Critical Section
+    NVIC_EnableIRQ(UART1_IRQn);
+    return;
+}
+
+// Get Command and ESP status replies
+void getreply()
+{
+    read_line();
+    sscanf(rx_line,replybuff);
+}
+ 
+// Read a line from the large rx buffer from rx interrupt routine
+void read_line() {
+    int i;
+    i = 0;
+// Start Critical Section - don't interrupt while changing global buffer variables
+    NVIC_DisableIRQ(UART1_IRQn);
+// Loop reading rx buffer characters until end of line character
+    while ((i==0) || (rx_line[i-1] != '\r')) {
+// Wait if buffer empty
+        if (rx_in == rx_out) {
+// End Critical Section - need to allow rx interrupt to get new characters for buffer
+            NVIC_EnableIRQ(UART1_IRQn);
+            while (rx_in == rx_out) {
+            }
+// Start Critical Section - don't interrupt while changing global buffer variables
+            NVIC_DisableIRQ(UART1_IRQn);
+        }
+        rx_line[i] = rx_buffer[rx_out];
+        i++;
+        rx_out = (rx_out + 1) % buffer_size;
+    }
+// End Critical Section
+    NVIC_EnableIRQ(UART1_IRQn);
+    rx_line[i-1] = 0;
+    return;
+}
+ 
+ 
+// Interupt Routine to read in data from serial port
+void Rx_interrupt() {
+    DataRX=1;
+// Loop just in case more than one character is in UART's receive FIFO buffer
+// Stop if buffer full
+    while ((esp.readable()) && (((rx_in + 1) % buffer_size) != rx_out)) {
+        rx_buffer[rx_in] = esp.getc();
+// Uncomment to Echo to USB serial to watch data flow
+        pc.putc(rx_buffer[rx_in]);
+        rx_in = (rx_in + 1) % buffer_size;
+    }
+    return;
+}
+ 
+ 
+// Interupt Routine to write out data to serial port
+void Tx_interrupt() {
+// Loop to fill more than one character in UART's transmit FIFO buffer
+// Stop if buffer empty
+    while ((esp.writeable()) && (tx_in != tx_out)) {
+        esp.putc(tx_buffer[tx_out]);
+        tx_out = (tx_out + 1) % buffer_size;
+    }
+    return;
+}
+
+void gettime()
+{
+    time_t seconds = time(NULL);
+    strftime(timebuf,50,"%H:%M:%S %a %d %b %y", localtime(&seconds));
+}
+
+void setRTC()
+{
+    t.tm_sec = (0);             // 0-59
+    t.tm_min = (minute);        // 0-59
+    t.tm_hour = (hour);         // 0-23
+    t.tm_mday = (dayofmonth);   // 1-31
+    t.tm_mon = (month-1);       // 0-11  "0" = Jan, -1 added for Mbed RCT clock format
+    t.tm_year = ((year)+100);   // year since 1900,  current DCF year + 100 + 1900 = correct year
+    set_time(mktime(&t));       // set RTC clock
+}
+// Analog in example
+void getsteps(){
     while(!IMU.accelAvailable());
         IMU.readAccel();
         ax=IMU.calcAccel(IMU.ax);
         ay=IMU.calcAccel(IMU.ay);
         az=IMU.calcAccel(IMU.az);
         a=sqrt(pow(ax, 2) + pow(ay, 2) + pow(az, 2));
-        pc.printf("a: %d", a);
         if (a>=threshold && flag==0){ // if it crosses threshold increment step by one and raise the flag
-            steps++; flag=1; 
-            pc.printf("steps: %i", steps);
+            steps+=1; flag=1; calories=steps/20;
+            pc.printf("steps: %i\n", steps);
         } 
 
         else if (a < threshold && flag==1){ // if flag is raised and threshold is not crossed , put that flag down.
             flag=0;
         }
-        return steps;
+        sprintf(Steps,"%2.3f",steps);
+        sprintf(Calories_burned, "%2.3f", calories);
 }
-    
-double getdistance(){
+void getdistance(){
     if (i==0){
         //initial reading made by the GPS
         gps.sample();
         buffer[i]= gps.longitude;
         buffer[i+1] = gps.latitude;
         i=i+2;
-//        pc.printf("First reading taken \n");
         if (buffer[2]==0 && buffer[3]==0){
             //second reading made by GPS
             gps.sample();
@@ -56,39 +390,11 @@
             float lon1d = buffer[1];
             float lat2d = buffer[2];
             float lon2d = buffer[3];
-            distance = object.distanceEarth(lat1d, lon1d, lat2d, lon2d);
-
-//            pc.putc(totalDistance);
-//            pc.putc(time_passed);
-            //pc.printf("Distance travelled: %f km", totalDistance);
-            //pc.printf("\n Distance travelled: %f miles", totalDistance * 0.621371);
-
+            d = object.distanceEarth(lat1d, lon1d, lat2d, lon2d);
             lat1d = buffer[2];
             lon1d = buffer[3];
             i=0;
         }
-        return distance;
-}
-
-
-int main()
-{
-    IMU.begin();
-    if (!IMU.begin()) {
-        pc.printf("Failed to communicate with LSM9DS1.\n");
-    }
-    IMU.calibrate(1);
-    clock_t start = clock();
-    dist_travel=getdistance();
-    totalDistance+=dist_travel;   
-
-    while(1) {
-       step_num=getsteps();
-       dist_travel=getdistance();
-       clock_t end = clock();
-       time_elapsed=end-start;
-       totalDistance+=dist_travel;
-       pc.printf("Distance travelled: %f km\n\rTime elapsed: %f s", totalDistance, time_elapsed/1000); 
-       clock_t start = clock(); 
-    }   
+        totalDistance+=d;
+        sprintf(Distance_travel, "%2.3f", totalDistance);
 }
\ No newline at end of file