write arduino script for Write a program to make the Arduin
write arduino script for :
Write a program to make the Arduino a clock. It should print time to the serial monitor every second (followed by a linefeed). The time should be in the format: hh: mm:ss h hours, m minutes, s seconds) You can print the time in 24 hr. format or 12 hr. format with the additional designations of AM and PM, your choice. Note you must print leading zeros if necessary, for example 3 minutes after 9 should be printed 09:03:00 Not 9:3:0 Assume your program begins executing at exactly 12 noon (12:00:00). Explain your code via comments in the code. Run this program manually to make sure it works, you need not run this program on an actual Arduino board. You may want to compile your program on the Arduino compiler to check for syntax errors (your option).Solution
int sec ;
int min ;
int hr ;
unsigned long milliseconds ;
void loop {
if(millis() - milliseconds >= 1000) { //if 1000 milliseconds passed
milliseconds = millis(); //update milliseconds that will be used in next iteration to compare eclapsed time
sec = sec + 1; //increase the second counter
if (sec == 60) { // if second counter is equal to 60, increase minuite counter and reset second counter
min = min + 1;
sec = 0;
}
if (min == 60) { // if minute counter is equal to 60, increase hour counter and reset minuite counter
hr = hr + 1;
min = 0;
}
if (hr == 24) // if second counter is equal to 24, reset hour counter
hr = 0;
String time = \"\"; declare and initialize time string
if (hr < 10) //if hour is single digit add leading zero
time = \"0\";
time = time + hr + \":\"; //add hour value to string
if (min < 10) //if minuite is single digit add leading zero
time = time + \"0\";
time = time + min + \":\"; // add minute to string
if (sec < 10) //if second is single digit add leading zero
time = time + \"0\";
time = time + sec; // add second to string
Serial.println(time); // print time
}
}
void setup(){
sec = 0;
min = 0;
hr = 0;
milliseconds = 0;
}
