/* 
    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.
	
    This mod makes the tree blink "water..." repeatedly, in Morse code,
    when the water level is low.
*/

#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 dit() {
    digitalWrite(flasher, LOW);
    delay(timescale);
    digitalWrite(flasher, HIGH);
    delay(timescale);
}

void dah() {
    digitalWrite(flasher, LOW);
    delay(3*timescale);
    digitalWrite(flasher, HIGH);
    delay(timescale);
}

void space() {
    delay(2*timescale);
}

void MorseWater() {
    // turn off lights
    digitalWrite(flasher, HIGH);
    space(); space(); space();

    // Flash a request in Morse code
    dit(); dah(); dah(); space();   // w
    dit(); dah(); space();          // a
    dah(); space();                 // t
    dit(); space();                 // e
    dit(); dah(); dit(); space();   // r
}

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.
        MorseWater();
    }
}