#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
HTTPClient http;
#define SCREEN_WIDTH 128 // Độ rộng của màn hình OLED
#define SCREEN_HEIGHT 64 // Độ cao của màn hình OLED
// Địa chỉ I2C của màn hình OLED
#define OLED_ADDR 0x3C
// Khởi tạo một đối tượng SSD1306 với kích thước màn hình 128x64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
void setup() {
// Khởi tạo giao tiếp I2C
Wire.begin();
Serial.begin(115200);
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
// Khởi tạo màn hình OLED
if(!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println(F("Màn hình OLED không kết nối được! Kiểm tra kết nối và địa chỉ."));
while (true); // Dừng lại nếu không kết nối được với màn hình OLED
}
// Delay ngắn để cho màn hình khởi động
delay(2000);
// Xóa màn hình
display.clearDisplay();
// Hiển thị thông báo khởi động
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.println("Hello, ESP32!");
// Hiển thị lên màn hình
display.display();
}
void loop() {
if ((WiFi.status() == WL_CONNECTED)) {
HTTPClient http;
http.begin("https://api.openweathermap.org/data/2.5/weather?id=1562693&appid=cee343d33e41970dd63c44b39c8620ab");
int httpCode = http.GET();
if (httpCode > 0) {
if(httpCode == HTTP_CODE_OK){
//Lấy dữ liệu từ http
String payload = http.getString();
//Chuyển đổi dữ liệu
JsonDocument doc;
deserializeJson(doc, payload);
//Lấy giá trị cần thiết từ file Json
double t = doc["main"]["temp"];
double tempC = (t - 32)*(5.0/9.0);
double h = doc["main"]["humidity"];
display.clearDisplay();
display.setCursor(0,0);
display.println("Nhiet do:");
display.setCursor(0,10);
display.println(tempC);
Serial.println(tempC);
//In độ ẩm;
display.setCursor(0,20);
display.println("Do am:");
display.setCursor(0,30);
Serial.println(h);
display.println(h);
display.display();
}
}
else {
Serial.println("Error on HTTP request");
}
http.end();
}
delay(50000);
}
Loading
ssd1306
ssd1306