i am making a project on my arduino uno. it is a ultrasonic sensor and when it gets a read below 80 it sets off two LEDS i hoped to have this project done by halloween because i wanted to have a pumpkin with this in it so when people come by the lights on the inside turn on it is a simple project but there is a problem. the sensor i have (HC-SRO4) gives off bad reads ever ounces in a while and this cause the LEDS to flash off or on at random times. is there a way to filter out these reads i will put my code below and an example of a read i would like it to filter out.
My code:
const int trig = 12;
const int echo = 13;
const int LED1 = 8;
const int LED6 = 3;
const int LED7 = 2;
int duration = 0;
int distance = 0;
void setup()
{
pinMode(trig , OUTPUT);
pinMode(echo , INPUT);
pinMode(LED1 , OUTPUT);
pinMode(LED6 , OUTPUT);
pinMode(LED7 , OUTPUT);
Serial.begin(9600);
}
void loop()
{
digitalWrite(trig , HIGH);
delayMicroseconds(1000);
digitalWrite(trig , LOW);
duration = pulseIn(echo , HIGH);
distance = (duration/2) / 28.5 ;
Serial.println(distance);
if ( distance <= 200 )
{
digitalWrite(LED1, HIGH);
}
else
{
digitalWrite(LED1, LOW);
}
if ( distance <= 100 )
{
digitalWrite(LED6, HIGH);
}
else
{
digitalWrite(LED6, LOW);
}
if ( distance <= 100 )
{
digitalWrite(LED7, HIGH);
}
else
{
digitalWrite(LED7, LOW);
}
}
Read i want to filter Red is what i want to filter
5
5
5
5
4
4
4
4
2
2
104
222
5
5
5
5
5
5
5