#include <Servo.h>
#include <dht.h>
#define DHT22_PIN 3
dht DHT;
Servo servo1, servo2;
const int systemStart = 7;
const int systemStatus = 4;
int ledState = HIGH;
int buttonState = LOW;
int lastButtonState = HIGH;
int reading;
int flag;
long lastDebounceTime = 0;
long debounceDelay = 50;
unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 1000;
void setup() {
Serial.begin(9600);
servo1.attach(6);
servo2.attach(5);
pinMode(systemStart, INPUT_PULLUP);
pinMode(systemStatus, OUTPUT);
pinMode(A0, INPUT_PULLUP);
startMillis = millis();
}
void loop() {
reading = digitalRead(systemStart);
if (reading != lastButtonState) {
lastDebounceTime = millis();
lastButtonState = reading;
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (buttonState != lastButtonState) {
buttonState = lastButtonState;
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(systemStatus, ledState);
}
}
}
if (ledState == HIGH) {
flag = 1;
systemFunction();
}
else {
currentMillis = millis();
if (currentMillis - startMillis >= period) {
startMillis = currentMillis;
Serial.println("System status = OFF");
}
}
}
void systemFunction() {
if (flag == 1) {
int chk = DHT.read22(DHT22_PIN);
int ptmValue = analogRead(A0);
ptmValue = map(ptmValue, 0, 1023, 0, 180);
currentMillis = millis();
if (currentMillis - startMillis >= period) {
startMillis = currentMillis;
Serial.println("System status = ON");
Serial.print("Temperature = ");
Serial.println(DHT.temperature, 1);
Serial.print("Humidity = ");
Serial.println(DHT.humidity, 1);
}
if (ptmValue > 0) {
servo1.attach(6);
servo2.attach(5);
servo1.write(ptmValue);
servo2.write(ptmValue);
}
else {
if (DHT.temperature < 25 && DHT.humidity < 50) {
servo1.attach(6);
servo2.attach(5);
servoSweeper();
}
else {
servo1.detach();
servo2.detach();
}
}
}
}
void servoSweeper() {
int rtnValue;
for (rtnValue = 0; rtnValue <= 180; rtnValue += 1) {
servo1.write(rtnValue);
servo2.write(rtnValue);
delay(5);
}
for (rtnValue = 180; rtnValue >= 0; rtnValue -= 1) {
servo1.write(rtnValue);
servo2.write(rtnValue);
delay(5);
}
}