#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTPIN 4 // กำหนดพินที่ต่อกับ DHT22
#define DHTTYPE DHT22
const char* ssid = "Wokwi-GUEST"; // ใส่ชื่อ WiFi ของคุณ
const char* password = ""; // ใส่รหัสผ่าน WiFi ของคุณ
const char* serverName = "http://YOUR_SERVER_IP:8000/api/temperature/";
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
dht.begin();
}
void loop() {
if(WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
String jsonPayload = "{\"temperature\":" + String(temperature) + ", \"humidity\":" + String(humidity) + "}";
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}
delay(60000); // ส่งข้อมูลทุก ๆ 60 วินาที
}