Skip to content

Instantly share code, notes, and snippets.

@sussan0416
Last active September 4, 2021 15:45
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 sussan0416/07dffdf9359381009ba049199f16be1b to your computer and use it in GitHub Desktop.
Save sussan0416/07dffdf9359381009ba049199f16be1b to your computer and use it in GitHub Desktop.
NTP時計 + 温湿度計
#include <ESP8266WiFi.h> // for WIFI
#include <time.h> // for time(), localtime()
// Wi-Fi設定
#define WIFI_SSID "your wi-fi ssid"
#define WIFI_PASSWORD "your wi-fi password"
// NTP設定
#define TIMEZONE_JST "JST-9" // Arduino/cores/esp8266/TZ.h
#define NTP_SERVER1 "ntp.nict.jpntp.nict.jp" // NTPサーバー
#define NTP_SERVER2 "ntp.jst.mfeed.ad.jp" // NTPサーバー
// LCD設定
#include <LCD_ST7032.h>
LCD_ST7032 lcd;
unsigned long millisecondsForDisplay = 0;
unsigned long millisecondsForSensor = 0;
// DHT11
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 14
#define DHTTYPE DHT11
DHT_Unified dht(DHTPIN, DHTTYPE);
void setup()
{
dht.begin();
lcd.begin();
String connectingMessage = "Connecting";
// Wi-Fiセットアップ
// WiFiネットワーク接続
if ((WiFi.status() != WL_CONNECTED)) {
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
while (WiFi.status() != WL_CONNECTED)
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(connectingMessage);
delay(500);
connectingMessage += ".";
if (connectingMessage.length() > 13) {
connectingMessage = "Connecting";
}
}
lcd.clear();
// 確認用にIPアドレスを表示
lcd.setCursor(0, 0);
lcd.print(WiFi.localIP());
delay(2000);
// NTP同期
configTzTime("JST-9", NTP_SERVER1, NTP_SERVER2);
}
void loop()
{
if (millis() < millisecondsForDisplay) {
// 指定した秒に達するまでは、時刻表示を維持
} else {
millisecondsForDisplay += 1000;
displayTime();
}
if (millis() < millisecondsForSensor) {
// 指定した秒に達するまでは、温湿度表示を維持
} else {
millisecondsForSensor += 5000;
displayTemperature();
}
delay(300);
}
void displayTime() {
// 現在時刻の取得
time_t timeNow = time(NULL);
struct tm* tmNow = localtime(&timeNow);
// 日付
char szDate[32];
strftime(szDate, sizeof(szDate), "%Y/%m/%d(%a)", tmNow);
// 時刻
char szTime[32];
strftime(szTime, sizeof(szTime), "%H:%M:%S", tmNow);
lcd.setCursor(0, 0);
lcd.print(szDate);
lcd.setCursor(1, 0);
lcd.print(szTime);
}
void displayTemperature() {
//// 温湿度表示
lcd.setCursor(1, 9);
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
lcd.print("____");
} else {
char temperature[32];
sprintf(temperature, "%2.1f", event.temperature);
lcd.print(temperature);
}
lcd.setCursor(1, 14);
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
lcd.print("__");
} else {
char humidity[32];
sprintf(humidity, "%2.0f", round(event.relative_humidity));
lcd.print(humidity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment