Skip to content

Instantly share code, notes, and snippets.

@me-no-dev
Last active July 21, 2016 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save me-no-dev/73dc073fccf174c697b65eee73b4706b to your computer and use it in GitHub Desktop.
Save me-no-dev/73dc073fccf174c697b65eee73b4706b to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <time.h>
const char * ssid = "********";
const char * password = "********";
#define getCompileTime() _getCompileTime(__DATE__, __TIME__)
struct tm * _getCompileTime(const char * compile_date, const char * compile_time){
const char * months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int year = atoi(compile_date+7),
month = 0,
day = atoi(compile_date+4),
hour = atoi(compile_time),
minute = atoi(compile_time+3),
second = atoi(compile_time+6);
int i;
for(i=0; i<12; i++){
if(memcmp(compile_date, months[i], 3) == 0){
month = i;
}
}
static struct tm * timeinfo = (struct tm *)malloc(sizeof(struct tm));
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month;
timeinfo->tm_mday = day;
timeinfo->tm_hour = hour;
timeinfo->tm_min = minute;
timeinfo->tm_sec = second;
mktime(timeinfo);
return timeinfo;
}
struct tm * getCurrentTime(){
time_t rawtime;
time (&rawtime);
return localtime(&rawtime);
}
void printTime(struct tm * t){
static char result[64];
// see: http://www.cplusplus.com/reference/ctime/strftime/
strftime (result,64,"%A, %B %d %Y %H:%M:%S",t);
Serial.printf("Time: %s\n", result);
}
extern "C" void system_set_os_print(uint8 onoff);
bool initTime(){
time_t rawtime;
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
uint8_t i = 0;
system_set_os_print(0);
while(time(&rawtime) == 0 && i++ < 100) delay(10);
system_set_os_print(1);
if(i==100){
Serial.println("Time Init Failed");
return false;
}
printTime(getCurrentTime());
return true;
}
void setup(){
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
Serial.print("Sketch Compile ");
printTime(getCompileTime());
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
os_printf("WiFi Failed!\n");
while(1){
delay(100);
}
}
initTime();
}
void loop(){
delay(1000);
printTime(getCurrentTime());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment