#include <ESP32Servo.h>
#include "DHTesp.h"
#define BLYNK_PRINT Serial
/* Fill in information from Blynk Device Info here */
#define BLYNK_TEMPLATE_ID "TMPL6KwPLbm0E"
#define BLYNK_TEMPLATE_NAME "Lad5"
#define BLYNK_AUTH_TOKEN "zuIHmpaGivqmmEp2WyjUVAvfkYiK7AmO"
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
const int DHT = 35, LED = 14, POTEN = 27, SERVO = 12;
int currentHumidity = 0, currentPoten = 0, degree = 0;
bool on_off = false; // สถานะระบบ (เปิด/ปิด)
Servo servo;
DHTesp dht;
BlynkTimer timer; // สร้าง Timer เพื่อแยกการทำงานออกจาก loop
void checkHumidity() {
if (on_off) {
int humidValue = dht.getHumidity();
if (humidValue != currentHumidity) {
currentHumidity = humidValue;
Blynk.virtualWrite(V2, currentHumidity);
}
}
}
void checkPoten() {
int potenValue = analogRead(POTEN);
int poten = map(potenValue, 0, 4095, 0, 180);
if (poten != currentPoten) {
currentPoten = poten;
Blynk.virtualWrite(V0, currentPoten);
}
}
BLYNK_CONNECTED()
{
Blynk.syncVirtual(V0);
Blynk.syncVirtual(V1);
Blynk.syncVirtual(V2);
}
BLYNK_WRITE(V0)
{
degree = param.asInt();
servo.write(degree);
Serial.print("V0 Value Received: ");
Serial.println(degree);
}
BLYNK_WRITE(V1)
{
on_off = param.asInt();
digitalWrite(LED, on_off);
Serial.print("V1 Value Received: ");
Serial.println(on_off);
}
BLYNK_WRITE(V2)
{
Serial.print("V2 Value Received: ");
Serial.println(param.asInt());
}
void setup() {
Serial.begin(115200);
servo.attach(SERVO);
dht.setup(DHT, DHTesp::DHT22);
servo.write(0);
pinMode(LED, OUTPUT);
pinMode(POTEN, INPUT);
Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, "blynk.cloud", 80);
// every 3 seconds
timer.setInterval(3000L, checkHumidity);
// every 100ms
timer.setInterval(100L, checkPoten);
}
void loop() {
Blynk.run();
timer.run();
}