简体   繁体   中英

what to do with unstable ultrasonic sensor values

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:)

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM