/* 
    waterlevel.pde
    Eric Ayars
    12/4/2011

    Used in conjuncion with a relay and a capacitive water level sensor to 
    flash the Christmas tree lights as an indicator of water level in the 
    tree-stand.
*/

#include <CapSense.h>

#define GOOD 425
#define FAIR 410

long level;                         // storage for C measurement value

CapSense sensor = CapSense(11,12);  // 470kOhm resistor between 11 and 12. 
                                    // Water sensor cap is between 12 and gnd.

byte flasher = 13;                  // pin controlling relay
int timescale = 500;                // everything happens in multiples of 0.5 second

void blink(int interval) {
    // turns relay off for timescale milliseconds, turns it back on, 
    // then waits interval.
    // Note that relay is NC, so HIGH turns lights off.
    digitalWrite(flasher, HIGH);
    delay(timescale);
    digitalWrite(flasher, LOW);
    delay(interval);
}

void setup() {

    pinMode(flasher, OUTPUT);
    digitalWrite(flasher, LOW);

    sensor.set_CS_AutocaL_Millis(0xFFFFFFFF);   // turn off autocalibrate
    sensor.set_CS_Timeout_Millis(5000);         // set timeout to 5 seconds
    // Serial.begin(9600);
}

void loop() {
    level = sensor.capSenseRaw(20);
    // Serial.print(level);
    // Serial.print('\n');

    if (level > GOOD) {
        // Make sure lights are on.
        digitalWrite(flasher, LOW);
        delay(timescale);
    } else if (level > FAIR) {
        // Water is low, but not horribly so.
        blink(10*timescale);
    } else {
        // Water is very low, possibly dry.
        blink(timescale);
    }
}