/* PINS */ #define RELAY_PIN 10 #define LED_PIN 2 #define SWITCH_PIN 6 #define WATER_PIN A1 /* CONSTANTS */ #define SHUTDOWN_DELAY (60 * 60) #define WATER_PRESENT 300 /* STATE VARIABLES */ /* Last switch state at startup * is set to -1 to trigger coffee * start at startup */ int last_switch_state = -1; /* We're not making coffee at startup */ int making_coffee = false; /* We didn't start yet */ long coffee_started_at = 0; /* FUNCTIONS */ /* return current timestamp in seconds */ long now() { return millis() / 1000; } /* return the switch state (on or off) */ int read_switch() { int new_state = digitalRead(SWITCH_PIN); /* latch if state changed */ if (new_state != last_switch_state) { delay(250); new_state = digitalRead(SWITCH_PIN); } return new_state; } /* return whether the water sensor is immersed */ int has_water() { int value = analogRead(WATER_PIN); Serial.print(" Water sensor: "); Serial.println(value); return (value > WATER_PRESENT); } /* start making coffee: * relay on, LED on */ void start_coffee() { /* First check if there's water */ if (!has_water()) { Serial.println(" No water"); error_blink(); return; } /* We have water, we can start */ Serial.println("Starting coffee"); digitalWrite(RELAY_PIN, HIGH); digitalWrite(LED_PIN, HIGH); /* store state */ making_coffee = true; /* store start time */ coffee_started_at = now(); } /* stop making coffee: * relay off, LED off */ void stop_coffee() { Serial.println("Stopping coffee"); digitalWrite(RELAY_PIN, LOW); digitalWrite(LED_PIN, LOW); /* store state */ making_coffee = false; /* discard start time */ coffee_started_at = 0; } /* Return true if we started making coffee * more than SHUTDOWN_DELAY seconds ago */ int timeout_reached() { return (now() - coffee_started_at > SHUTDOWN_DELAY); } /* Blink LED on and off four times * Used to indicate "no water" error */ void error_blink() { int i; for (i = 0; i < 4; i++) { digitalWrite(LED_PIN, HIGH); delay(250); digitalWrite(LED_PIN, LOW); delay(250); } } /* Arduino setup * Done once at startup */ void setup() { Serial.begin(9600); /* Configure relay and LED pins as output */ pinMode(RELAY_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); /* Configure switch pin as input, * enable pullup resistor */ pinMode(SWITCH_PIN, INPUT_PULLUP); /* Configure water sensor pin as input */ pinMode(WATER_PIN, INPUT); } /* Arduino loop * Executed endlessly as long as the * Arduino is powered */ void loop() { int switch_state = read_switch(); /* Check if the switch has been toggled */ if (switch_state != last_switch_state) { Serial.println("Switch toggled"); /* It has been. Store the new state */ last_switch_state = switch_state; /* And start or stop making coffee, * depending on if we were */ if (making_coffee) { stop_coffee(); } else { start_coffee(); } } else { /* The switch wasn't toggled. Verify, if * we're making coffee, whether it's * time to stop. */ if (making_coffee && timeout_reached()) { Serial.println("Timeout reached"); stop_coffee(); } } }