Hi. I'm having some weird issues with code. Looking in serial monitor variables vent_on and vent_off does not get set after pressing button and time that is supposed to be 10 seconds sometimes is 7 seconds sometimes 1second... sometmes when i restart arduino button works ok for first time. Any ideas and suggestions?
#include <dht.h>
dht DHT;
#define DHT22_PIN 9
float hum;
float temp;
int vent_on = 0;
int vent_off = 0;
int vent_on_btn = 2;
int vent_off_btn = 4;
int vent_on_btn_state = 0;
int vent_off_btn_state = 0;
int vent_on_period = 10000;
int vent_off_period = 10000;
unsigned long time_now_on = 0;
unsigned long time_now_off = 0;
void setup()
{
pinMode(vent_on_btn, INPUT);
pinMode(vent_off_btn, INPUT);
digitalWrite(vent_on_btn, HIGH);
digitalWrite(vent_off_btn, HIGH);
Serial.begin(9600);
}
void loop()
{
vent_on_btn_state = digitalRead(vent_on_btn);
if (vent_on_btn_state == LOW) {
vent_on = 1;
vent_off = 0;
Serial.println("vent ON pressed");
} else {
if(vent_on == 1){
if(millis() >= time_now_on + vent_on_period){
time_now_on += vent_on_period;
vent_on = 0;
Serial.println("vent ON period over");
}
}
}
vent_off_btn_state = digitalRead(vent_off_btn);
if (vent_off_btn_state == LOW) {
vent_on = 0;
vent_off = 1;
Serial.println("vent OFF pressed");
} else {
if(vent_off == 1){
if(millis() >= time_now_off + vent_off_period){
time_now_off += vent_off_period;
vent_off = 0;
Serial.println("vent OFF period over");
}
}
}
int chk = DHT.read22(DHT22_PIN);
hum = DHT.humidity;
temp= DHT.temperature;
Serial.print("H: ");
Serial.print(hum);
Serial.print(" %, T: ");
Serial.print(temp);
Serial.print(" C ; V_off: ");
Serial.print(vent_off);
Serial.print(" ; V_on: ");
Serial.print(vent_on);
Serial.println(" ");
if(vent_off == 1 && hum > 75){
Serial.println("VENT OFF! DO NOTHING");
}else if(vent_on == 1 && hum > 75){
Serial.println("VENT ALREADY ON");
}else if (vent_on == 0 && vent_off == 0 && hum >75){
Serial.println("TURN ON VENT");
}
}