Skip to content

Instantly share code, notes, and snippets.

@a-c-t-i-n-i-u-m
Created February 26, 2016 17:04
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 a-c-t-i-n-i-u-m/2c951f2668489bf2d678 to your computer and use it in GitHub Desktop.
Save a-c-t-i-n-i-u-m/2c951f2668489bf2d678 to your computer and use it in GitHub Desktop.
NTP+AP+HTTP esp8266 example
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
// time
uint64_t epoch = 0;
const char timeZoneName[] = "Asia/Tokyo";
const int16_t timeZoneOffsetMinutes = 9 * 60;
// connection info
const char CON_SSID[] = "ssid";
const char CON_PASSWD[] = "passwd";
// AccessPoint settings
const char AP_SSID[] = "esp8266";
const char AP_PASSWD[] = "12345678";
// NTP sync settings
const uint16_t UDP_PORT = 2390;
IPAddress NTP_SERVER(133, 243, 238, 163); // ntp.nict.jp NTP server
const uint8_t NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE];
WiFiUDP udp;
// HTTP server implementation
ESP8266WebServer server(80);
void handleRequest()
{
digitalWrite(BUILTIN_LED, LOW);
char response[256];
uint32_t currentTime = epoch + round(millis() / 1000);
sprintf(response, "<script>setTimeout(function(){location.reload();}, 1000);</script>%s%02d%02d %s %02d:%02d:%02d",
timeZoneOffsetMinutes >= 0 ? "+" : "-", abs(timeZoneOffsetMinutes / 60), abs(timeZoneOffsetMinutes % 60), timeZoneName,
(currentTime % 86400L) / 3600, (currentTime % 3600) / 60, currentTime % 60);
server.send(200, "text/html", response);
digitalWrite(BUILTIN_LED, HIGH);
}
//
// init process
//
void setup()
{
pinMode(BUILTIN_LED, OUTPUT); // initialize onboard LED as output
digitalWrite(BUILTIN_LED, HIGH);
Serial.begin(115200);
Serial.print("\n\nConnecting to ");
Serial.print(CON_SSID);
WiFi.begin(CON_SSID, CON_PASSWD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("success!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// enable Access Point
WiFi.softAP(AP_SSID, AP_PASSWD);
// start server
server.on("/", handleRequest);
server.begin();
// ntp sync
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011;
packetBuffer[1] = 0;
packetBuffer[2] = 6;
packetBuffer[3] = 0xEC;
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.begin(UDP_PORT);
udp.beginPacket(NTP_SERVER, 123);
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
while(!udp.parsePacket()) { delay(100); } // wait response
udp.read(packetBuffer, NTP_PACKET_SIZE); // read
epoch = ((word(packetBuffer[40], packetBuffer[41]) << 16) | word(packetBuffer[42], packetBuffer[43]))
- 2208988800UL// epoch offset
+ 60 * timeZoneOffsetMinutes// timezone
- round(millis() / 1000);// system offset
}
void loop()
{
server.handleClient();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment