2020年8月11日 星期二

ESP32 NodeMCU 32S 取得網路時間

 ESP32 NodeMCU 32S 取得網路時間

資料來源

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/


 先安裝NTP的library  NTP Client library forked by Taranais

程式碼:https://gist.github.com/clive520/d79293310fc4a99e62122c648d552239


/*********

  Rui Santos

  Complete project details at https://randomnerdtutorials.com

  Based on the NTP Client library example

*********/


#include <WiFi.h>

#include <NTPClient.h>

#include <WiFiUdp.h>


// Replace with your network credentials

const char* ssid     = "book";

const char* password = "12345678";


// Define NTP Client to get time

WiFiUDP ntpUDP;

NTPClient timeClient(ntpUDP);


// Variables to save date and time

String formattedDate;

String dayStamp;

String timeStamp;


void setup() {

  // Initialize Serial Monitor

  Serial.begin(9600);

  Serial.print("Connecting to ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  // Print local IP address and start web server

  Serial.println("");

  Serial.println("WiFi connected.");

  Serial.println("IP address: ");

  Serial.println(WiFi.localIP());


// Initialize a NTPClient to get time

  timeClient.begin();

  // Set offset time in seconds to adjust for your timezone, for example:

  // GMT +1 = 3600

  // GMT +8 = 28800

  // GMT -1 = -3600

  // GMT 0 = 0

  timeClient.setTimeOffset(28800); //台灣時區要用28800

}

void loop() {

  while(!timeClient.update()) {

    timeClient.forceUpdate();

  }

  // The formattedDate comes with the following format:

  // 2018-05-28T16:00:13Z

  // We need to extract date and time

  formattedDate = timeClient.getFormattedDate();

  Serial.println(formattedDate);


  // Extract date

  int splitT = formattedDate.indexOf("T");

  dayStamp = formattedDate.substring(0, splitT);

  Serial.print("DATE: ");

  Serial.println(dayStamp);

  // Extract time

  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);

  Serial.print("HOUR: ");

  Serial.println(timeStamp);

  delay(1000);

}

沒有留言:

張貼留言

聲寶卡式濾心頭蓋

 https://www.ruten.com.tw/item/show?22027794089976 在這裡買的接頭 https://www.ruten.com.tw/item/show?21814839221595 【品名】台製優質濾心頭蓋 (適用3M、EVERPURE濾心)功...