-2

building a poop box for my cat with automatic door.

im using an HC-SR04 ultrasonic sensor with Arduino mega.

i have a sensor inside of an enclosed box(to sense if my cat is stuck inside, or stay open while cat is inside)

the inside sensor will fluctuate 67-68cm most of the time, however randomly it will throw in a value significantly less like 50cm, which in my program is designed to open up because it passed a threashold for 'nothing to be inside' and because of this my door keeps opening. how do i get around this.

my only solutions in my head is:

  • adding approx 5-10 sets of value in an array and take the average(since its scanning fast enough)

any other solutions? thanks :)

  • 2
    The signal being provided by your sensor is the distance to a real object, plus some noise. That noise comes either from outside noise, or errors within the sensor itself. Since the noise seems to be transient, a low-pass filter sounds appropriate. Your sliding window average is a type of low pass filter. Any other LPF implementations should also work. – JohnFilleau Nov 28 '21 at 18:22
  • Alternatively you could just make sure you have 5-10 consecutive reads of <50cm, before acting on it. – gre_gor Nov 29 '21 at 00:30

1 Answers1

0

These random values could be nothing but noise as your receiver may be sensing other source of ultra sound.

Here is an example, where I take multiple readings (poop_measurements measurements) and then take the average over it:

long getDuration() {
  digitalWrite(TRIGGER, LOW);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);

  digitalWrite(TRIGGER, LOW);
  return pulseIn(ECHO, HIGH);
}

void loop() {
  float duration = 0, distance = 0;
  int poop_measurements = 10;
  for (int i = 0; i < poop_measurements; i++) {
    duration += getDuration();
  }
  duration = duration/poop_measurements;
  distance = (duration / 2) / 29.1;

  if (distance < 30 ){
    digitalWrite(RELAY, HIGH);
  } else{  
    digitalWrite(RELAY, LOW);
  }

  Serial.print("CM: ");
  Serial.println(distance);

}
Nabil Akhlaque
  • 192
  • 1
  • 8