Craig Evans / Mbed 2 deprecated RTC

Dependencies:   mbed

Committer:
eencae
Date:
Thu Aug 07 13:13:02 2014 +0000
Revision:
0:9f741d395d17
Initial commit.; ; Reads Unix time as a string over serial and uses it to update the time on the RTC.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
eencae 0:9f741d395d17 1 #include "mbed.h"
eencae 0:9f741d395d17 2
eencae 0:9f741d395d17 3 Serial serial(USBTX,USBRX);
eencae 0:9f741d395d17 4
eencae 0:9f741d395d17 5 void serialISR(); // ISR that is called when serial data is received
eencae 0:9f741d395d17 6 void setTime(); // function to set the UNIX time
eencae 0:9f741d395d17 7 int setTimeFlag = 0; // flag for ISR
eencae 0:9f741d395d17 8
eencae 0:9f741d395d17 9 char rxString[16]; // buffer to store received string
eencae 0:9f741d395d17 10
eencae 0:9f741d395d17 11 int main()
eencae 0:9f741d395d17 12 {
eencae 0:9f741d395d17 13 serial.attach(&serialISR); // attach serial ISR
eencae 0:9f741d395d17 14 char buffer[30]; // buffer used to store time string
eencae 0:9f741d395d17 15
eencae 0:9f741d395d17 16 set_time(0); // initialise time to 1st January 1970
eencae 0:9f741d395d17 17
eencae 0:9f741d395d17 18 while(1) {
eencae 0:9f741d395d17 19
eencae 0:9f741d395d17 20 time_t seconds = time(NULL); // get current time
eencae 0:9f741d395d17 21 // format time into a string (time and date)
eencae 0:9f741d395d17 22 strftime(buffer, 30 , "%X %D", localtime(&seconds));
eencae 0:9f741d395d17 23 // print over serial
eencae 0:9f741d395d17 24 serial.printf("Time = %s\n",buffer);
eencae 0:9f741d395d17 25 wait(1.0); // delay for a second
eencae 0:9f741d395d17 26
eencae 0:9f741d395d17 27 if (setTimeFlag) { // if updated time has been sent
eencae 0:9f741d395d17 28 setTimeFlag = 0; // clear flag
eencae 0:9f741d395d17 29 setTime(); // update time
eencae 0:9f741d395d17 30 }
eencae 0:9f741d395d17 31 }
eencae 0:9f741d395d17 32
eencae 0:9f741d395d17 33 }
eencae 0:9f741d395d17 34
eencae 0:9f741d395d17 35 void setTime() {
eencae 0:9f741d395d17 36 // print time for debugging
eencae 0:9f741d395d17 37 serial.printf("set_time - %s",rxString);
eencae 0:9f741d395d17 38 // atoi() converts a string to an integer
eencae 0:9f741d395d17 39 int time = atoi(rxString);
eencae 0:9f741d395d17 40 // update the time
eencae 0:9f741d395d17 41 set_time(time);
eencae 0:9f741d395d17 42 }
eencae 0:9f741d395d17 43
eencae 0:9f741d395d17 44 void serialISR() {
eencae 0:9f741d395d17 45 // when a serial interrupt occurs, read rx string into buffer
eencae 0:9f741d395d17 46 serial.gets(rxString,16);
eencae 0:9f741d395d17 47 // set flag
eencae 0:9f741d395d17 48 setTimeFlag = 1;
eencae 0:9f741d395d17 49 }