Set and read RTC through the serial console.
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 Serial pc(USBTX,USBRX); //UART0 via OpenSDA 00003 DigitalOut myled(LED1); 00004 Ticker myticker; 00005 time_t mytime; 00006 volatile uint8_t myflag = 0; 00007 #define DATE_20200222_222222 1582377742 // 2020/2/22 22:22:22 00008 00009 void processSerialCommand(); 00010 00011 void setflag(void) 00012 { 00013 myflag = 1; 00014 } 00015 00016 int main() 00017 { pc.baud(115200); 00018 time_t seconds; 00019 seconds = time(NULL); 00020 if (seconds < DATE_20200222_222222) { 00021 set_time(DATE_20200222_222222); 00022 } 00023 myticker.attach(&setflag,5); 00024 while(1) { 00025 if(pc.readable()) { 00026 processSerialCommand(); 00027 } 00028 if(myflag) { 00029 mytime = time(NULL); 00030 pc.printf("RTC time: %s\r\n",ctime(&mytime)); 00031 myflag = 0; 00032 } 00033 } 00034 } 00035 00036 void processSerialCommand() 00037 { 00038 char c = pc.getc(); 00039 switch(c) { 00040 case 'T': 00041 // Command to set RTC time 00042 // Command format: TYYMMDDHHMMSS 00043 // Example: 2012 Oct 21 1:23pm is T121021132300 00044 struct tm tme; 00045 time_t newTime; 00046 00047 // Parse incomming 12 ASCII charaters into time_t 00048 // no error checking for numeric values in YYMDDHHMMSS fields, so be careful! 00049 c = pc.getc(); 00050 tme.tm_year = c - '0'; 00051 c = pc.getc(); 00052 tme.tm_year = 10*tme.tm_year; 00053 tme.tm_year += c-'0'; 00054 tme.tm_year += 100; //Years are counted from 1900! 00055 c = pc.getc(); 00056 tme.tm_mon = c - '0'; 00057 c = pc.getc(); 00058 tme.tm_mon = 10*tme.tm_mon; 00059 tme.tm_mon += c-'0'-1; //corrected by -1 due to a stupid error 00060 c = pc.getc(); 00061 tme.tm_mday = c - '0'; 00062 c = pc.getc(); 00063 tme.tm_mday = 10*tme.tm_mday; 00064 tme.tm_mday += c-'0'; 00065 c = pc.getc(); 00066 tme.tm_hour = c - '0'; 00067 c = pc.getc(); 00068 tme.tm_hour = 10*tme.tm_hour; 00069 tme.tm_hour += c-'0'; 00070 c = pc.getc(); 00071 tme.tm_min = c - '0'; 00072 c = pc.getc(); 00073 tme.tm_min = 10*tme.tm_min; 00074 tme.tm_min += c-'0'; 00075 c = pc.getc(); 00076 tme.tm_sec = c - '0'; 00077 c = pc.getc(); 00078 tme.tm_sec = 10*tme.tm_sec; 00079 tme.tm_sec += c-'0'; 00080 newTime = mktime(&tme); 00081 set_time(newTime); 00082 pc.printf("RTC set to: %s\r\n",ctime(&newTime)); 00083 } 00084 while(pc.readable()) { 00085 pc.getc(); // clear serial buffer 00086 } 00087 }
Generated on Wed Sep 21 2022 17:31:01 by
1.7.2