I need help as I think I'm missing some fundamental information regarding the use of millis.
We have a simple set up using a JSN-SR04T sensor that triggers an LED when someone is within a distance range.
However, as this is outside, the readings quite often reads anomalies and triggers the LED. What I'm looking to do is add code to only trigger the LED if someone is within that range for 1 sec.
I am a complete beginner so go easy, here is my code so far:
// defines pins numbers
const int trigPin = 6;
const int echoPin = 5;
const int ledPin = 9;
// defines variables
long duration;
int distance;
int triggerDistance;
void setup() {
pinMode(trigPin, OUTPUT); //Sets the trigPin as an Output
pinMode(echoPin, INPUT); //Sets the echoPin as an Input
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// CLears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
//Sets the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(30);
digitalWrite(trigPin, LOW);
// Reads rhe echoPin, returns the sound wave travek time in microseconds
duration = pulseIn(echoPin, HIGH);
//Calculating the distance
distance = duration*0.034/2;
triggerDistance = distance;
if (triggerDistance >= 60 && triggerDistance <= 80) {
digitalWrite(ledPin, HIGH);
delay(5000);
}
else{
digitalWrite(ledPin, LOW);
}
//Prints the distance
Serial.print("distance: ");
Serial.println(distance);
}
This code currently lights the LED as soon as someone is in range. Instead you need to start a timer and then check if has been longer than 1 seconds before turning on the LED.