#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#define DHTPIN 33
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverName = "http://api.thingspeak.com/update";
String apiKey = "SSU4WLCO2VR43441"; //เอา API ตัวเองมาใส่++++++++++++
unsigned long lastTime = 0;
unsigned long timerDelay = 10000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");
// Random seed is a number used to initialize a pseudorandom number generator
randomSeed(analogRead(33));
}
void loop() {
float T = dht.readTemperature();
//Send an HTTP POST request every 10 seconds
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1=" + String(T);//เปลี่ยน random เป็น T
int httpResponseCode = http.POST(httpRequestData); // Send HTTP POST request
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}