Showing posts with label Arduino. Show all posts
Showing posts with label Arduino. Show all posts

Saturday, 18 July 2015

Updating a real time clock via GPS

RTC's are bloody handy but can be a pain in the arse to update or set accurately. So I've made a simple little but handy little program to automatically update my favorite DS3231 RTC modules directly from the awesomely accurate GPS time signals. It makes them so much better to use. Low cost GPS modules are here. The days of putting the current time, adjusted for compilation error into your code are over. 

All you need is a  NMEA GPS module (I used a $10 GY-NEO6MV2), your choice of Arduino and a DS3231 RTC Module.
I wont go into detail about how to communicate with the GPS or the DS3231. Maybe I will later, but that is so well documented elsewhere on the net, that there is really little point. 
To get the DS3231 going, follow this well thought out guide from Tronixstuff. 
To get the GPS running, go to Git hub and download the TinyGPS++ library. 
If you haven't got it already, you'll also need the Time library from arduino.org. 
***NOTE 2017*** Updates to the time library have broken this code. To run it now you'll need the old time library and a early version of the Arduino IDE pre 1.6.1! This blog is neglected, and I'll probably never fix the code to run in the new IDE. Sorry. 


Get the connections right.

Once you have your GPS and and RTC connected correctly, copy and paste this code, making sure to set your GPS baud, timezone and the correct software serial pins for the GPS. I've used 14(A0) for Rx from the GPS. You don't need to worry about Tx to the GPS for this one. 



Pin13 will light solid on success and flash rapidly on failure. Or you can watch the serial monitor for a more verbose indication. There will be a few micro seconds error generated between reading the GPS time and writing that to the RTC. But it should be negligible. I haven't even bothered trying to measure it. If that error is unacceptable, then you'll need a more accurate clock for your project anyway. I have included a basic checksum test to ensure that the RTC matches GPS time. Checksum failure will cause pin 13 to flash.


Enjoy.