Skip to content

Instantly share code, notes, and snippets.

@delta-G
Created August 29, 2015 17:25
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 delta-G/210dc7177f1584271287 to your computer and use it in GitHub Desktop.
Save delta-G/210dc7177f1584271287 to your computer and use it in GitHub Desktop.
#define SEC_PER_MIN (60)
#define SEC_PER_HOUR (60ul * 60)
#define SEC_PER_DAY (24ul * 60 * 60)
unsigned long countdownTime = 0;
void setup(){
Serial.begin(9600);
delay(20);
Serial.println(F("Enter Days"));
int days = getInputFromUser();
Serial.println(F("Enter Hours"));
int hours = getInputFromUser();
Serial.println(F("Enter Minutes"));
int minutes = getInputFromUser();
Serial.println(F("Enter Seconds"));
int seconds = getInputFromUser();
countdownTime = seconds + (minutes * SEC_PER_MIN) + (hours * SEC_PER_HOUR) + (days * SEC_PER_DAY);
}
void loop(){
static unsigned long lastTick = millis();
unsigned long currentMillis = millis();
// Way more accurate timing this way than with delay
// Also allows for code to do other things during countdown
if (currentMillis - lastTick >= 1000){
lastTick += 1000;
countdownTime--;
displayTime(countdownTime);
}
if (countdownTime == 0){
Serial.println(F("Countdown Finished"));
while(1); // infinite loop... lock up program until reset
}
}
// blocks program for input from user via serial
// returns the number entered as an int
int getInputFromUser(){
char buf[5];
int index = 0;
while(Serial.available() < 1); // DO nothing until serial arrives
buf[index] = Serial.read();
while (buf[index] != '\n'){
if(Serial.available()){
buf[++index] = Serial.read();
}
// Don't run over the end of buf
if (index == 4){
buf[index] = '\n';
break;
}
}
// Received a null, Serial transmission is over
return atoi(buf);
}
//Prints time to serial in D:H:M:S format
void displayTime(unsigned long aTime){
int seconds = aTime % SEC_PER_MIN;
int minutes = (aTime % (SEC_PER_HOUR)) / SEC_PER_MIN;
int hours = (aTime % (SEC_PER_DAY) / (SEC_PER_HOUR));
int days = aTime / (SEC_PER_DAY);
Serial.println(F("tick"));
Serial.print(days);
Serial.print(F(" : "));
Serial.print(hours);
Serial.print(F(" : "));
Serial.print(minutes);
Serial.print(F(" : "));
Serial.println(seconds);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment