## Thursday, 22 May 2014

### Arduino Clock

Yes finally I am doing something that is a bit roboty. I managed to get my hands on an LCD shield for Arduino. Once my brother had worked out the correct pins to use we plugged it into an Arduino Mega we had lying around.

I immediately did a bit of research and it was really easy to turn it into a clock. There are quite a number of clock tutorials out there but I think a lot of their code is a bit overcomplicated. I was able to get one going with only page of code and only using the Liquid Crystal library.

Here is the code:

``` //Chris Fryer 2014 this code is in the public domain. // http://myrobotnstuff.blogspot.com.au/ //Thanks baldengineer for millis() taming //http://www.baldengineer.com/ #include <LiquidCrystal.h> long time = 0; int secs = 0; int mins = 0; int hours = 0; //The number of second passed so far today (12 hours) //eg. 12 noon and midnight = 0 long starttime = 18000; int interval=1000; unsigned long previousMillis=0; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() {   // set up the LCD's number of columns and rows:   lcd.begin(16, 2);   // Print a message to the LCD.   lcd.print("I'm a clock!"); } void loop() {      // Get snapshot of time    unsigned long currentMillis = millis();    // Millis() resets to 0 after 50 days or something. It also    // screwed up my calculations that I wasn't able to reset it.    // This if statement does three things.    // 1. account for the reset    // 2. allows me to only update the display when it needs    // updating    // 3. makes calculating time easier (I hate maths)    // Thanks baldengineer for code    //http://goo.gl/4YSE71    if ((unsigned long)(currentMillis - previousMillis) >= interval)    {       // It's time to do something!       time++;       // Use the snapshot to set track time until next event       previousMillis = currentMillis;       lcd.clear();       secs = time + starttime;       if (secs>43199)       {         starttime = 0;         time = 0;         secs = time + starttime;       }              if (secs>60)       {         mins = secs / 60;         secs = secs % 60;       }              if (mins>60)       {         hours = mins / 60;         mins = mins % 60;       }                    lcd.print(hours);       lcd.print(":");       //shove a zero in so it formats nicely       if (mins<10)         lcd.print("0");       lcd.print(mins);       //shove a zero in so it formats nicely       lcd.print(":");       if (secs<10)         lcd.print("0");       lcd.print(secs);    } } ```

hizzer