David Ehrlich / breath_test

breath_test.cpp

Committer:
dehrlich
Date:
2016-11-02
Revision:
0:dd2e484220ac

File content as of revision 0:dd2e484220ac:

#include "mbed.h"
#include <vector> //added for Lab1 part 3
#include <algorithm> //added for Lab1 part 3
#include <assert.h>     /* assert */
AnalogIn windSensor(p17);
DigitalOut myled(LED1);
Timer t, q;
vector<float> b;
vector<float> c;
template<typename T>

void pop_front(std::vector<T>& vec)
{
    assert(!vec.empty());
    vec.erase(vec.begin());
}

float give_breath(void) {
    float a = 0.0;
    float d = 0.0; //return time for fractional breathes
    float e = 0.0;
    int i;
    float thresh;
    for(i = 0; i<20; i++){
        a = a + windSensor;
    }
    a = a/20.0; //get first baseline reading
    thresh = a*3.0; //theshold to start breathe timer (ideal multiplier is between 2-3)
    t.start();
    while(1){
        if(t.read() <= 3.0){
          wait(0.1); //necessary to give sensor time to be polled
          if(windSensor > thresh){
            q.start();
            myled = 1;
            for(i = 0; i<10; i++){
                c.push_back(windSensor);
            }
            for(i=0; i<10; i++){
                e = e + c[i];
            }
            e = e/10.0; //provides slope of 10 most recent samples
            while( (e > thresh) && (q.read() < 1.0)){

              pop_front(c);//remove the oldest element
              c.push_back(windSensor);
              for(i=0; i<10; i++){
                e = e + c[i];
              }
              e = e/10.0; //provides slope of 10 most recent samples
              
              }
              d = q.read();
          if(q.read() > 1.0){ //breathe was greater than thresh and lasted more than 1 sec
            return 1.0; //full breath
          }
          else{
              return d; //partial breath
          }
        }
      }
      else{
        return 0.0; //no breath in 3 seconds
        }
    } 

}