Simple example to set RTC interactively
Dependencies: mbed
main.cpp
- Committer:
- icserny
- Date:
- 2016-01-07
- Revision:
- 0:d04730d28a80
File content as of revision 0:d04730d28a80:
#include "mbed.h" Serial pc(USBTX,USBRX); //UART0 via OpenSDA DigitalOut myled(LED1); Ticker myticker; time_t mytime; volatile uint8_t myflag =0; void processSerialCommand(); void setflag(void) { myflag = 1; } int main() { set_time(1451736661); myticker.attach(&setflag,5); while(1) { if(pc.readable()) { processSerialCommand(); } if(myflag) { mytime = time(NULL); pc.printf("RTC time: %s\r\n",ctime(&mytime)); myflag = 0; } } } void processSerialCommand() { char c = pc.getc(); switch(c) { case 'T': // Command to set RTC time // Command format: TYYMMDDHHMMSS // Example: 2012 Oct 21 1:23pm is T121021132300 struct tm tme; time_t newTime; // Parse incomming 12 ASCII charaters into time_t // no error checking for numeric values in YYMDDHHMMSS fields, so be careful! c = pc.getc(); tme.tm_year = c - '0'; c = pc.getc(); tme.tm_year = 10*tme.tm_year; tme.tm_year += c-'0'; tme.tm_year += 100; //Years are counted from 1900! c = pc.getc(); tme.tm_mon = c - '0'; c = pc.getc(); tme.tm_mon = 10*tme.tm_mon; tme.tm_mon += c-'0'-1; //corrected by -1 due to a stupid error c = pc.getc(); tme.tm_mday = c - '0'; c = pc.getc(); tme.tm_mday = 10*tme.tm_mday; tme.tm_mday += c-'0'; c = pc.getc(); tme.tm_hour = c - '0'; c = pc.getc(); tme.tm_hour = 10*tme.tm_hour; tme.tm_hour += c-'0'; c = pc.getc(); tme.tm_min = c - '0'; c = pc.getc(); tme.tm_min = 10*tme.tm_min; tme.tm_min += c-'0'; c = pc.getc(); tme.tm_sec = c - '0'; c = pc.getc(); tme.tm_sec = 10*tme.tm_sec; tme.tm_sec += c-'0'; newTime = mktime(&tme); set_time(newTime); pc.printf("RTC set to: %s\r\n",ctime(&newTime)); } while(pc.readable()) { pc.getc(); // clear serial buffer } }