False readings on the ultrasonic sensor

Hi guys, I'm making an Arduino car that uses an ultrasonic sensor to dodge obstacles. The problem is that suddenly the sensor starts showing false data, marking 0 when it should not. I am using the HC-SR04 sensor (i´m using an arduino UNO), this is my code:

int duration;
int distance;

void setup() {
pinMode(4, OUTPUT);
pinMode(6, INPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(4, HIGH);
delay(1);
digitalWrite(4, LOW);

duration = pulseIn(6, HIGH);
distance = (duration/2)/29;
Serial.println(distance);

if(distance <= 15){
  digitalWrite(9, HIGH);
  digitalWrite(10, LOW);
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(50);
}else{
  digitalWrite(9, LOW);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
}
}

2023-04-23

Welcome to the forum

Not the cause of the problem, but why do this ?

digitalWrite(4, HIGH);
delay(1);
digitalWrite(4, LOW);

It is the pulse that Trig sends and that Echo will later read and so the distance can be measured (Trig is connected to pin 4 and Echo is connected to pin 6)

The program is working exactly as expected, although the sensor or wiring may not be.

Declare duration unsigned long, as required by pulseIn(); Otherwise it overflows your "int" declaration.

This line:
distance = (duration/2)/29;

is equivalent to

distance = (duration/58);

Which is an integer divide. Any value of duration less that 58 results in distance = 0. Fix that by doing floating point division, for example

float distance = duration/58.0;

Do you know about NewPing library?
https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home

Thank you very much for helping me, but now instead of 0 I get 0.93 ._.
2023-04-23 (1)
`

Check or redo your wiring, and test the sensor operation with a reflecting surface at various distances.

Please post a photo of your setup.

This might be your problem. If you delay too long, pulseIn() could miss the rising edge of the echo pulse and result in a timeout (0). The typical delay is:

digitalWrite(4, HIGH);
delayMicroseconds(10);
digitalWrite(4, LOW);
1 Like

Kindly share the schematic

of course

No wonder you are having problems!

The Arduino is not a power supply, and the 5V output cannot be used to power motors or servos. Neither can a computer USB socket. The electrical noise from the motors creates all sorts of havoc, including interfering with sensor operation.

A 4xAA battery pack will work for the motors and save the Arduino and/or the USB port from damage.

oh, ok, thank you

sp. "schematic"

Sorry, I was not specific enough with my question. It was the use of delay() rather than delayMicroseconds() that I was querying

Is that I was based on a tutorial​:sweat_smile::sweat_smile:

Thank you very much, it finally works!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.