// Sensor pin and readings
int sensorPin = 5;
const int numReadings = 10;
int sensorValues[numReadings];
int sensorAverage;
int sensorThreshold = 100;
int sensorBaseValue = 438;
// Sip and puff detection variables
boolean sipThresholdCrossed = false;
boolean puffThresholdCrossed = false;
boolean sipDetected = false;
boolean puffDetected = false;
// General program behavior
boolean debug = true;
void setup() {
pinMode(sensorPin, INPUT);
Serial.begin(9600);
Keyboard.begin();
}
void loop() {
readSensor();
processSensor();
// Sip has been detected - do something
if(sipDetected) {
Serial.println("# Sip detected");
Keyboard.write(' ');
sipDetected = false;
}
// Puff has been detected - do something
if(puffDetected) {
Serial.println("# Puff detected");
puffDetected = false;
}
if(debug)
erial.println(sensorAverage);
}
/****************************************
readSensor()
Read sensor value several times, store
average in globally-accessible variable
*****************************************/
void readSensor() {
// Take a few readings
for(int i=0; i<numReadings; i++) {
int v = analogRead(sensorPin);
sensorValues[i] = v;
}
// Find average of all readings
int total = 0;
for(int i=0; i<numReadings; i++) {
total += sensorValues[i];
}
sensorAverage = total/numReadings;
}
/*******************************************
Process the sensor data to derive sipping
and puffing activity.
********************************************/
void processSensor() {
// While data is hovering in safe zone
if(sipThresholdCrossed == false && puffThresholdCrossed == false) {
// Check if the data has crossed either the sip or puff threshold
if(sensorAverage <= sensorBaseValue - sensorThreshold) {
sipThresholdCrossed = true;
} else if(sensorAverage >= sensorBaseValue + sensorThreshold) {
puffThresholdCrossed = true;
}
// If data has drifted above or below safe zone
} else {
// Check if the data has returned to safe zone
if(sensorAverage <= sensorBaseValue + sensorThreshold && sensorAverage >= sensorBaseValue - sensorThreshold) {
if(sipThresholdCrossed) {
sipDetected = true;
sipThresholdCrossed = false;
}
if(puffThresholdCrossed) {
puffDetected = true;
puffThresholdCrossed = false;
}
}
}
}