#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>
// Khởi tạo màn hình LCD với địa chỉ I2C và kích thước 16x2
LiquidCrystal_I2C lcd(0x27, 16, 2);
float gia_xang = 0; // Biến để lưu giá xăng
String buyPrice; // Biến để lưu giá mua vàng SJC
String sellPrice; // Biến để lưu giá bán vàng SJC
// Hàm gửi yêu cầu HTTP GET và trả về phản hồi
String httpGetRequest(const char* url) {
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
String payload;
if (httpCode > 0) { // Kiểm tra nếu yêu cầu thành công
payload = http.getString(); // Lấy dữ liệu trả về
Serial.println(payload); // In dữ liệu lên Serial để kiểm tra
} else {
Serial.println("Lỗi HTTP"); // Thông báo lỗi nếu không kết nối được
}
http.end();
return payload;
}
// Hàm phân tích JSON để lấy giá xăng từ API
void parseFuelPrice(const String& payload) {
DynamicJsonDocument doc(4096); // Khởi tạo tài liệu JSON
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
gia_xang = doc["data"][0]["vung_1_xang_ron_95_v"]; // Lấy giá xăng 95
} else {
Serial.println("Lỗi phân tích JSON giá xăng");
}
}
// Hàm phân tích JSON để lấy giá vàng từ API
void parseGoldPrice(const String& payload) {
DynamicJsonDocument doc(4096); // Khởi tạo tài liệu JSON
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
JsonArray dataArray = doc["DataList"]["Data"];
for (JsonObject item : dataArray) {
if (item["@n_7"] == "VÀNG MIẾNG SJC (Vàng SJC)") { // Tìm giá vàng SJC
buyPrice = item["@pb_7"].as<String>(); // Lấy giá mua
sellPrice = item["@ps_7"].as<String>(); // Lấy giá bán
break;
}
}
} else {
Serial.println("Lỗi phân tích JSON giá vàng");
}
}
void setup() {
Serial.begin(115200);
lcd.init(); // Khởi tạo màn hình LCD
lcd.backlight(); // Bật đèn nền LCD
// Kết nối WiFi
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print("."); // Hiển thị chấm chờ kết nối
}
Serial.println(" Đã kết nối!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
// Lấy dữ liệu giá xăng từ API và phân tích
String fuelPayload = httpGetRequest("https://wifeed.vn/api/du-lieu-vimo/hang-hoa/gia-xang-dau-trong-nuoc?page=1&limit=100&apikey=demo");
parseFuelPrice(fuelPayload);
// Lấy dữ liệu giá vàng từ API và phân tích
String goldPayload = httpGetRequest("http://api.btmc.vn/api/BTMCAPI/getpricebtmc?key=3kd8ub1llcg9t45hnoh8hmn7t5kc2v");
parseGoldPrice(goldPayload);
// Hiển thị dữ liệu lên LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Xang 95: ");
lcd.print(gia_xang); // Hiển thị giá xăng
lcd.setCursor(0, 1);
lcd.print("SJC Mua: ");
lcd.print(buyPrice); // Hiển thị giá mua vàng SJC
lcd.setCursor(0, 2);
lcd.print("SJC Ban: ");
lcd.print(sellPrice); // Hiển thị giá bán vàng SJC
delay(8000); // Cập nhật lại sau 10 giây
} else {
Serial.println("Đang kết nối lại WiFi...");
WiFi.begin("Wokwi-GUEST", "", 6);
delay(5000); // Thử kết nối lại sau 5 giây
}
}