Go Down

Topic: HC-SR04 Ultrasonic Sensor Help (Read 124 times) previous topic - next topic

GXPrototype

Apr 25, 2018, 03:54 am Last Edit: Apr 25, 2018, 03:55 am by GXPrototype
So, I am a new user to Arduino, but I had programming experience in the past. I decided to mess with the Ultrasonic Sensor, but when I ran the results, they were interesting. Even though I saw the sensor was looking at nothing, the sensor recorded that it was looking at something. I wonder if anyone can help me fix this issue with the sensor. Thanks.

This is the code:

int Echo = A4;
int Trig = A5;

int middleDistance = 0;
int Distance_test() {
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(20);
  digitalWrite(Trig, LOW);
  float Fdistance = pulseIn(Echo, HIGH);
  Fdistance = Fdistance/58;
  Serial.println(Fdistance);
  return (int)Fdistance;
}

void setup() {
  Serial.begin(9600);

}

void loop() {
  middleDistance = Distance_test();
 
  if(middleDistance <= 6) {
    Serial.println("OH YESSSS!! I AM NOT BLIND");
  }
  else {
    Serial.println("I AM BLIND!!!!");
  }
  delay(1000);
}




Also, the distance is in centimeters.

The picture displays the serial printings.

DaveEvans

#1
Apr 25, 2018, 08:11 am Last Edit: Apr 25, 2018, 09:41 pm by DaveEvans
This sensor does occasionally return unexpected values.  Your code should be able to recognize and reject outliers. 

Use the median of a few samples (see NewPing library) or, say, reject all zeros and any reading that is not within x cm of the last "known good" reading (provided the expected distances don't change "a lot" quickly), or...... 

Also, you may find it helpful to set the pulseIn() timeout to something other than the default one second.

Idahowalker

To get a really set of good readings from the SR04's I have soldered a 103 (.1uF) cap across the  Vcc and Gnd pins between the Tx and Rx sensors. I then found 2 sensors that, when there is nothing to detect, return different values. I mounted the 2 sensors on top of each other SR04T and SR04B. SR04T has a 1 inch offset, set back, from SR04B, so I compensate, in code, for the inch difference. I, using new ping, ping SR04B and if it returns a value I ping SR04T and figure out if the same value has been returned.

I use NewPing and I ping using SR04B.ping_in() and SR04T.ping_in(). I do not use a delay between pinging SR04B and SR04T.

If there is an object to detect and both sensors return the same figure, 'you' are there.

The important this is to make sure each sensor you choose do not tend to return the same noise value.

I, also, use one of those cheap MicroWaveMotion Detectors to gate on the SR04's.

Go Up