Skip to content

Instantly share code, notes, and snippets.

@maxhawkins
Created May 16, 2010 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxhawkins/32c18c5b1786dec42275 to your computer and use it in GitHub Desktop.
Save maxhawkins/32c18c5b1786dec42275 to your computer and use it in GitHub Desktop.
#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