Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <FreqCounter.h>
/** Constants **/
const int NUMBER_OF_CALIBRATION_CYCLES = 10; // Number of 250ms calibrations to determine the baseline sensor value
const int FUDGE_FACTOR = 1.5; // Deviation from baseline that triggers switch
const int TIMEOUT = 2000; // Number of loop cycles to deactivate fan between presses
enum STATE { ACTIVATED, DEACTIVATED };
/** Pins **/
const int relayPin = 12;
const int ledPin = 13; // activates when switch is triggered
/** Variables **/
unsigned long baseline;
int timeSincePress;
STATE state;
void setup() {
pinMode(relayPin, OUTPUT);
pinMode(ledPin, OUTPUT);
// Initialize the frequency counter on pin 5
// Read from counter every 250ms to see how many pulses there are from the fan
FreqCounter::start(250);
baseline = getSensorBaseline();
}
void loop() {
unsigned long currentValue = getSensorValue();
if(currentValue < (baseline * FUDGE_FACTOR)) {
activateSwitch();
} else if(state == ACTIVATED) {
if(timeoutExpired()) {
deactivateSwitch();
} else {
tickTimeout();
}
}
}
unsigned long getSensorValue() {
unsigned long frequency;
// Idle until the 250ms have elapsed
while (FreqCounter::f_ready == 0)
// Grab most recent frequency value
frequency = FreqCounter::f_freq;
return frequency;
}
unsigned long getSensorBaseline() {
unsigned long average;
// Poll the sensor NUMBER_OF_CALIBRATION_CYCLES times, find the average
for(int i=0; i < NUMBER_OF_CALIBRATION_CYCLES; i++)
average += getSensorValue();
average /= NUMBER_OF_CALIBRATION_CYCLES;
return average;
}
void activateSwitch() {
digitalWrite(relayPin, HIGH);
digitalWrite(ledPin, HIGH);
state = ACTIVATED;
timeSincePress = 0;
}
void deactivateSwitch() {
digitalWrite(relayPin, LOW);
digitalWrite(ledPin, LOW);
state = DEACTIVATED;
}
boolean timeoutExpired() {
timeSincePress > TIMEOUT;
}
void tickTimeout() {
timeSincePress++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment