#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_SSD1306.h>
#include "DHTesp.h"
#include <HTTPClient.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
DHTesp dhtSensor;
#define SCREEN_WIDTH 128 // OLED 寬度像素
#define SCREEN_HEIGHT 64 // OLED 高度像素
#define LOGO_HEIGHT 50
#define LOGO_WIDTH 50
// 設定OLED
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const int DHT_PIN = 16;
// Line Notify 的 Access Token
const char* LINE_NOTIFY_ACCESS_TOKEN = "4MoqPh94RvUo8L0WjEB4YLuXEbgeq36W63ZGitAb0QL";
void sendLineNotify(String message) {
WiFiClientSecure client;
const char* host = "notify-api.line.me";
const int httpsPort = 443;
if (!client.connect(host, httpsPort)) {
Serial.println(F("Connection failed"));
return;
}
String url = "/api/notify";
url += "?message=" + message;
client.println("POST " + url + " HTTP/1.1");
client.println("Host: " + String(host));
client.println("Authorization: Bearer " + String(LINE_NOTIFY_ACCESS_TOKEN));
client.println("Content-Type: application/x-www-form-urlencoded");
client.println("Cache-Control: no-cache");
client.println();
Serial.println(F("Line Notify message sent!"));
}
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// 偵測是否安裝好OLED了
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // 一般1306 OLED的位址都是0x3C
Serial.println(F("SSD1306 allocation failed"));
for (;;)
; // Don't proceed, loop forever
}
display.clearDisplay(); // 清除畫面
delay(1000);
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
display.clearDisplay();
display.setTextSize(1); // 設定文字大小
display.setTextColor(1); // 1:OLED預設的顏色
display.setCursor(5, 0); // 設定起始座標
// 在OLED上顯示溫濕度資訊
display.print("Temp: " + String(data.temperature, 2) + "C");
display.setCursor(5, 10);
display.print("Humidity: " + String(data.humidity, 1) + "%");
// 在串口輸出
Serial.println("Temp: " + String(data.temperature, 2) + "C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
// 在OLED上顯示訊息
display.setCursor(5, 30);
display.print("Sending Line Notify...");
// 發送Line Notify訊息
sendLineNotify("Temp: " + String(data.temperature, 2) + "C, Humidity: " + String(data.humidity, 1) + "%");
// 在OLED上顯示完成訊息
display.setCursor(5, 50);
display.print("Line Notify Sent!");
// 顯示在OLED上
display.display();
// 等待一段時間
delay(5000);
}
Loading
ssd1306
ssd1306