Hi everyone,
I'm pretty new to the Arduino and I'm struggling with a part of my code.
I'm trying to turn the LED on, if the value X on my sensor is below 500, and turn it off when it is above.
Now I want to implement a timer (from a serial terminal input for values 1-50 seconds). And here comes the issue. I want that whenever the LED is supposed to turn OFF (the value X is above 500), the LED will remain ON for the duration of the timer that was set (using the serial terminal) and then after the timer expires it turns the LED off. Unfortunatelly, my code turns the LED off immedietely after the sensor value X is above 500.
Could you please help me with this issue?
Thank you!
int X = 0;
long timer = 4000; //begins with 4 seconds
unsigned long timeMillis;
unsigned long previousTime = 0;
void setup() {
Serial.begin(9600);
Serial.println("Enter timer - from 1 to 50 seconds: ");
//LED output
pinMode(8, OUTPUT);
}
void loop() {
X = analogRead(1);
if(Serial.available()) {
//reading the input command for on time
String time = Serial.readStringUntil('\n');
time.trim();
timer = time.toInt();
if(timer >= 1 && timer <= 50){
timer = timer * 1000;
}
else {
Serial.println("Your number doesn't fit in the range");
timer = 4000;
}
}
//Turn the LED on if it's below 500
if(X < 500){
digitalWrite(8, HIGH);
}
//Turn the LED off if it's above 500
else if (X >= 500){
timeMillis = millis();
Serial.println(timeMillis);
Serial.println(previousTime);
if ((timeMillis - previousTime) >= timer){
previousTime = timeMillis;
digitalWrite(8, LOW);
}
}
}
Are you doing this to avoid rapidly turning on and off when the analog input is near the detection threshold? A timer is not the best solution for that. Use hysteresis instead.