A tutti sarà capitato di dover configurare un chip RTC con l’orario corrente… il progetto di oggi risolve questa esigenza!
Il progetto
RTCSetup è formato da due elementi:
[checklist]
- una GUI, scritta in C# e in esecuzione sul PC
- uno sketch in esecuzione su Arduino, il quale è collegato all’RTC
[/checklist]
GUI e sketch comunicano via seriale tramite un semplice protocollo. I sogenti di entrambi gli elementi sono disponibili nel mio repository su Github.
Arduino e RTC
Ho scelto di utilizzare la libreria RTClib di Adafruit per interfacciarmi ai chip RTC DS1307, sicuramente i più diffusi in ambito hobbistico. Il collegamento tra Arduino e l’integrato avviene via bus I2C:
Per una spiegazione dettagliata del collegamento e del funzionamento della libreria, vi rimando al tutorial ufficiale.
Lo sketch Arduino riceve i comandi dal PC via seriale, li esegue e restituisce una risposta.
Protocollo
Come detto, la comunicazione tra la GUI e Arduino avviene tramite un semplice protocollo composto da 4 comandi:
Comando: ##
Il primo comando inviato dopo la connessione, serve al PC per verificare che ci sia collegato un dispositivo “compatibile”. Arduino deve rispondere con !!
Comando: ?V
Comando per ottenere la versione dello sketch in esecuzione. Arduino risponde con la stringa definita come costante iniziale:
#define VERSION "1.0" |
Comando: ?T
Comando per ottenere l’orario attuale letto dall’RTC. Arduino risponde con una stringa nel formato dd/MM/yyyy hh:mm:ss.
Comando: !TddMMyyyyhhmmss
Comando per impostare l’orario dell’RTC. Arduino risponde con OK.
GUI
La GUI, sviluppata in C#, dialoga con Arduino utilizzando il protocollo descritto sopra e ha tre funzionalità:
[checklist]
- imposta data/ora corrente
- imposta data/ora scelte dell’utente
- ottiene e visualizza data/ora attuali dell’RTC
[/checklist]
Per prima cosa è necessario selezionare la porta seriale alla quale è connesso Arduino e premere CONNECT. Se la connessione ha esito positivo (comandi ## e ?V) nella barra di stato verrà visualizzata la versione dello sketch.
Il primo display è sempre allineato all’orario corrente del PC. Cliccando sul pulsante a destra (freccia rossa) è possibile configurare l’RTC con tale orario:
Utilizzando invece il pulsante con la freccia verde, è possibile ottenere l’orario corrente dall’RTC:
Infine è possibile, tramite il controllo date-time picker centrale, selezionare data/ora a piacere e inviare tale orario all’RTC:
Note tecniche
Ho utilizzato il metodo descritto in questo mio tutorial per utilizzare un font custom e includerlo nell’applicazione.
Ho misurato il tempo impiegato (150ms) dallo sketch Arduino per impostare l’orario una volta inviato il comando dalla GUI: per questo il codice C# invia il comando !T passando l’orario attuale + 1 secondo quando i millisecondi attuali sono 850.
while (DateTime.Now.Millisecond != 850) Thread.Sleep(1); string command = "!T" + time.AddSeconds(1).ToString("ddMMyyyyHHmmss"); serialPort.WriteLine(command); |
You are the man! Been waiting for something simple like this for setting my rtc’s. Thanks again for sharing!
Where I can downloas RTCsetup GUI?
Thanks
Hi Antonio, you can download a pre-compiled version of my program from Github:
https://github.com/lucadentella/RTCSetup/tree/master/VisualStudio/RTCSetup/RTCSetup/bin/Debug
(you need only RTCSetup.exe)
Hi, thanks for sharing this nice project – very useful 🙂 May I ask a question?…. I have updated the Arduino Sketch to use the RTC DS3231 which is very similar – the only difference is that ‘day’ in the DS1307 library becomes ‘date’ in the DS3231 library – all compiles fine but the computer end doesn’t successfully set the RTC desite reporting that it has done so – wondernig if there is anything I need to change in the VB code to get this working? Thanks.
Hi! well… no if your sketch can correctly “parse” the string my app sends and set the fields in the RTC. I don’t have a DS3231, which library are you using on Arduino side?
Hi Again, Whilst I havn’t got this working with the DS3231 yet I have got it working with the DS1307 – very nice.
One cool update might be to automatically update the RTC every second so you can see how this relates to the system time with ease 🙂
Hi, Thanks for the reply – the library I’m using is this one: https://gist.github.com/jeje/2021145 – it looks like the day of week element of this library might be tha main difference and is causing the problems?
Hi Luca,
OK, it was the Day of Week element that was throwing things out – splicing a ‘0’ into the end of set_time solved that one :-)… would still be great to see RTC time update every second as per System Time…. how do we do that ?
Hi Luca,
thanks for your great job. It works fine on 2 different Arduino Mega 2560.
It doesn’t work on a Pro Micro with ATmega32U4. The ATmega32U4 features build-in USB functionality, instead a additional USB-Controller like the Mega.
Is this already the problem or could it be with the serial buffer size?
Hi JH, unfortunately I don’t have a Leonardo or similar to test the sketch at the moment… did you get any errors?
Am I correct in thinking that this is windows only?
I agree with Devin – this is so incredibly useful but I was forced onto Linux when Windows continued to crash regularly, even after a complete re-install.
It might run under Wine I guess but, so far, I haven’t had a lot of success with that.
Your ENC28J60 tutorial series is also proving to be incredibly helpful and, as far as I have got with it, everything has worked ‘straight out of the box’.
Thanks Luca…
Hi Duncan
thanks for your feedback! I developed the RTCSetup client using .Net, maybe you can run it on Linux using Mono. I’m going to develop my next projects using Java so they should be more portable on different OSes.
Thanks Luca
I took a look at Mono but didn’t understand a word of it (in my 60s and no background in computing, but techie in the days of valves!).
Could you add this to your list of Java projects – It really is an incredibly useful.
If it could set all the RTCs on the network, using Ethernet or WiFi (it’s just easier sometimes if things have their own RTC to act at certain intervals) that would be a real killer, but I doubt it’s possible.
Keep the tutorials coming…
Hola que tal. mira traté de correr tu boceto pero me marca un error donde dice que el RTC_sd1307 no tiene un miembro begin en la libreria.no eh podido corregirlo. Utilizo arduino uno.
Hi! Did you install the RTClib from Adafruit?
I really have some bad luck…
I doesn’t work for me bcs some reason RTC app crash. it does connect to board, it does read (wrong) time/date from ds1307 but when I hit SET button it goes to “not responding”…
Luca,
è possibile per far girare la una GUI in C# sul Mac?
Grazie
Hi Luca,
I installed the GUI and uploaded the sketch.
The sketch works fine if i use the IDE terminal, it responds on all commands.
Using the GUI is gets the correct version (1.0) and the RTC time.
But when i want to write the new time using the GUI it seems that GUI ‘hangs’.
The mouse cursor keeps waiting for the program to finisch.
I am using Windows8.1
Harry
Just wanted to say thanks for this. The clocks had changed and I needed to update the time and didn’t have the time myself. Downloaded this, changed to DS3231 and worked first time.
Perfecto!
(Must add DCF77 to my new clock!)
salve luca,
il mio nome è angelo. ho realizzato il tuo rtcsetup mami sono accorto che manca del passaggio in automatico dell’ora legale/solare. come posso risolverlo?
Ciao Angelo, purtroppo visto che la data di cambio ora varia ogni anno, l’unica possibilità è aggiungere qualche controllo manuale (pulsanti…) per cambiare l’ora manualmente.
Hi
very nice projet thank you 🙂
I have a small clock based on a RTC PCF8563,
Can you make an adaptation of your setup program for the PCF8563 because I do not know the Visual C but I know how to program in Pascal Delphi is that the adaptation to this language is difficult?
To help me, you can quote me the methods of dialogue between the RTC and your setup program in the program Source C.
Hi Mic, you have to change the Arduino sketch, the VisualC program only communicates with Arduino, it doesn’t know which RTC is connected.
Ciao,stavo utilizzando questo tuo progetto ,ma quando imposto l’orario il tempo della conferma varia da 3 a minuti e il modulo rtc è di conseguenza sempre in ritardo,nvece quando richiedo l’ora è immediato.
Utilizzo arduino uno R3 con il modulo tiny rtc v1.1 basato su ds1307.
La cartella visual studio l’ho solo scompattata,non devo installare niente penso?
Grazie
Ciao Mauro, no, dovrebbe essere sufficiente lanciare il programma… strano che impieghi 3min per configurare l’orario, da me è istantaneo
Ciao,potrebbe un problema di sistema operativo,io utilizzo windows 8.1.Se volessi inviare la stringa tramite terminale,mi riesci a dire la stringa perchè ci provo,ma non mi funziona .Grazie
Updated, simple improvements and fixed crash.
serialManager.disconnect();
connected = false;
updateUI();
}
lbRTCTime.Text = serialManager.getRTCTime();
}
public void btGet_Click(object sender, EventArgs e)
{
lbRTCTime.Text = serialManager.getRTCTime();
}
private void btSetSystem_Click(object sender, EventArgs e)
{
lbSystemTime.Text = DateTime.Now.ToString(“dd/MM/yyyy HH:mm:ss”);
dtpCustom.Value = DateTime.Now;
serialManager.setRTCTime(dtpCustom.Value);
lbRTCTime.Text = serialManager.getRTCTime();
}
Hello, i found `RTCSetup.exe` would went wrong on win10. So i write a python version to set RTC datetime precisely.
see https://github.com/def-fun/RTCSetup/tree/master/Python
Thanks for your share.
Thanks, great job! I approved your merge request