Created
September 6, 2020 18:35
-
-
Save mgruben/d7e56d21cb436706e62801b7382a33b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define our physical setup | |
const int EARLIER_PIN = 13; | |
const int LED_PIN = 8; | |
const int HAVE_FED_PIN = 2; | |
// Define some configuration | |
// The "units" of our program | |
#define SECONDS 1000 | |
#define HOURS 3600000 | |
// Seconds for testing | |
// Hours for production | |
const unsigned long UNIT = HOURS; | |
const unsigned long TICKS = 24; | |
const unsigned long INTERVAL_MS = UNIT * TICKS; | |
// Declare some state-tracking variables | |
int haveFedButtonPressed = 0; | |
int alertSoonerButtonPressed = 0; | |
boolean alertSoonerButtonActive = false; | |
long previousMillis = 0; | |
void setup() { | |
pinMode(LED_PIN, OUTPUT); | |
pinMode(HAVE_FED_PIN, INPUT); | |
pinMode(EARLIER_PIN, INPUT); | |
} | |
boolean itHasBeen(unsigned long intervalMillis) { | |
unsigned long currentMillis = millis(); | |
if ((unsigned long)(currentMillis - previousMillis) >= intervalMillis) { | |
previousMillis = currentMillis; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
void alertSooner(long unit) { | |
previousMillis -= UNIT; | |
// Guard against underflow (yes, it would take a while) | |
if (previousMillis == UNIT) { | |
previousMillis = 0; | |
} | |
} | |
void loop() { | |
// Maybe alert the human to feed the fish | |
if (itHasBeen(INTERVAL_MS)) { | |
// Turn the LED ON | |
digitalWrite(LED_PIN, HIGH); | |
} | |
// Check if the human told us they fed the fish | |
haveFedButtonPressed = digitalRead(HAVE_FED_PIN); | |
if (haveFedButtonPressed) { | |
// Turn the LED OFF | |
digitalWrite(LED_PIN, LOW); | |
} | |
// Check if the human told us to alert 1 UNIT sooner | |
alertSoonerButtonPressed = digitalRead(EARLIER_PIN); | |
if (alertSoonerButtonPressed && !alertSoonerButtonActive) { | |
alertSooner(UNIT); | |
alertSoonerButtonActive = true; | |
} | |
// Try to de-bounce the button | |
if (!alertSoonerButtonPressed) { | |
alertSoonerButtonActive = false; | |
} | |
// Wait some time | |
// TODO: it would be better for battery life to enter some | |
// low-power state, which we would exit on a button press. | |
delay(50); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment