#include <WiFi.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
#include <HTTPClient.h> // 使用HTTPClient替代WebSocket
// Wokwi模拟WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// HTTP服务器配置(电脑本地)
const char* serverIP = "192.168.1.100"; // Wokwi服务器IP
const int serverPort = 80; // 服务器端口
const char* serverPath = "/data"; // 请求路径
// 配置参数
#define DHT_PIN 4
#define DHT_TYPE DHT22
#define LCD_ADDRESS 0x27
#define UPDATE_INTERVAL 2000
// 创建对象
DHT dht(DHT_PIN, DHT_TYPE);
LiquidCrystal_I2C lcd(LCD_ADDRESS, 16, 2);
HTTPClient http;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(100);
lcd.init();
lcd.backlight();
dht.begin();
Serial.println("Connected to WiFi");
Serial.println("IP: " + WiFi.localIP().toString());
}
void loop() {
float temp = dht.readTemperature();
float hum = dht.readHumidity();
// 显示在LCD上
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: " + String(temp, 1) + " C");
lcd.setCursor(0, 1);
lcd.print("Hum: " + String(hum, 1) + " %");
// 发送数据到服务器
if (WiFi.status() == WL_CONNECTED) {
http.begin(serverIP, serverPort, serverPath);
http.addHeader("Content-Type", "application/json");
// 构建JSON数据
String jsonData = "{\"temp\":" + String(temp, 1) + ",\"hum\":" + String(hum, 1) + "}";
// 发送POST请求
int httpCode = http.POST(jsonData);
if (httpCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpCode);
Serial.print("Response: ");
Serial.println(http.getString());
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpCode);
}
http.end();
} else {
Serial.println("WiFi disconnected");
}
delay(UPDATE_INTERVAL);
}