#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST"; // Thay thế bằng SSID của bạn
const char* password = ""; // Thay thế bằng mật khẩu của bạn
LiquidCrystal_I2C lcd(0x27, 20, 4); // Địa chỉ I2C của LCD, số cột = 20, số hàng = 4
const char* ipinfoUrl = "https://ipinfo.io/json";
void setup() {
lcd.init(); // Khởi tạo LCD
lcd.backlight(); // Bật đèn nền
Serial.begin(115200);
// Kết nối Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Hiển thị thông tin địa chỉ IP, quốc gia và thành phố
fetchIPInfo();
}
void loop() {
// Không có gì trong vòng lặp chính
}
void fetchIPInfo() {
HTTPClient http;
http.begin(ipinfoUrl); // Bắt đầu yêu cầu HTTP
int httpCode = http.GET(); // Thực hiện yêu cầu GET
if (httpCode > 0) { // Nếu yêu cầu thành công
String payload = http.getString(); // Lấy chuỗi JSON trả về
Serial.println(payload); // In ra chuỗi JSON để kiểm tra
// Phân tích JSON
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
String ip = doc["ip"].as<String>(); // Lấy địa chỉ IP
String city = doc["city"].as<String>(); // Lấy thành phố
String country = doc["country"].as<String>(); // Lấy quốc gia
// Hiển thị thông tin lên LCD
lcd.clear(); // Xóa màn hình
lcd.setCursor(0, 0);
lcd.print("IP: " + ip); // In địa chỉ IP
lcd.setCursor(0, 1);
lcd.print("City: " + city); // In thành phố
lcd.setCursor(0, 2);
lcd.print("Country: " + country); // In quốc gia
} else {
Serial.print("Error in JSON parsing: ");
Serial.println(error.f_str());
}
} else {
Serial.printf("Error on HTTP request: %s\n", http.errorToString(httpCode).c_str());
}
http.end(); // Kết thúc yêu cầu
}