Ultrasonic Sensor HCSR-04

Hi everyone,

I wonder if you can help me, I have this code below using ultrasonic sensor HCSR-04. My problem is I am only getting a printout of zero on the serial monitor.```

int trigPin = A0;
int echoPin= A1;
int pingTravelTime;
int dt = 2;
int dt1 = 10;
int dt2 = 25;

void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds (dt1);
digitalWrite(trigPin, HIGH);
delayMicroseconds(dt1);
digitalWrite(trigPin, LOW);
pingTravelTime = pulseIn(echoPin, HIGH);
delay(dt2);
Serial.println(pingTravelTime);

}type or paste code here

Welcome! You have an interesting project, but first please read the advice in the topic "How to get the best from this forum". There is a proper way to post code, this allows us to help you. Taking what you posted and putting into a readable form takes a lot of time many do not want to spend. It will only take you another 10 seconds after your figure it out. l have no clue as to what each hardware device is or how it interacts with your code, post an annotated schematic, the language of electronics, showing how you have wired it, not pictures such as frizzy (wiring) drawings they are useless for troubleshooting. Do include links to "Technical information" on the hardware parts, links to sales outlets like azon are next to useless. Doing this will have a big positive effect on your answers and will improve the accuracy of the answer a lot.

Check this out:

I would sure like to help you but since you did not take the time to read the forum guidelines I will not burn the time trying to figure out the gibberish you posted. All I can say at this point is good luck!

Hi! Welcome to the Forum.

I agree with gilshultz that you should have read "How to get the best out of this Forum", but since I've already spent some time reading your code, here's my 5 cents:

  1. you don´t need analog pins to use this sensor and pulsein() expects an int as the first parameter. So, you can either still use A0 and A1 physical pins but use their digitalself ID (A0=14 and A1=15) OR choose another pair of digital pins;

  2. pulsein() returns an unsigned long type. So pingTravelTime should obey this type

Test the code version below:

int trigPin = 14;
int echoPin= 15;
unsigned long pingTravelTime;
int dt = 2;
int dt1 = 10;
int dt2 = 25;

void setup() {
  //Serial Port begin
  Serial.begin (9600);
  //Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds (dt1);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(dt1);
  digitalWrite(trigPin, LOW);
  pingTravelTime = pulseIn(echoPin, HIGH);
  delay(dt2);
  Serial.println(pingTravelTime);
}

You can use A0 anywhere you would use 14. It's just a defined constant. They're not special names for only analog purposes.

analogRead(14) reads A0
digitalWrite(A0) writes digital on A0.
for (int i=0; i < A0; i++) Serial.print(i); will print 0 - 13

1 Like

If you want to see a bar graph representation of the numbers, try this:

#define trigPin A0
#define echoPin A1

long duration;
int distance;
int wall = 290;

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // create trigger pulse
  digitalWrite(trigPin, LOW);         // turn off pulses
  delayMicroseconds(2);               // pause before transmitting
  digitalWrite(trigPin, HIGH);        // transmit pulses...
  delayMicroseconds(10);              // ...for 10 microseconds
  digitalWrite(trigPin, LOW);         // turn off pulses
  duration = pulseIn(echoPin, HIGH);  // time the echo

  for (int i = 0; i < duration / wall; i++) { // create graph of echo
    Serial.print("*");
  }
  for (int i = 0; i < 80 - (duration / wall); i++ ) { // fill the cube to 100
    Serial.print(" ");
  }
  Serial.println("|");
  delay(100);
}

Hi, @chito1623
Have you looked at the NewPing library, it does it all for you.

Tom... :smiley: :+1: :coffee: :australia:

chito1623,

I tried the code that you posted in post #1.
I can confirm that your code did work, and correctly displayed the 'pingTravelTime' in microseconds.

However, I was able to get it to display zero, by disconnecting the 'trigPin' wire from Arduino A0 pin.

I think you need to check your wiring.

1 Like

Thanks, because this is my first time. I will take your advice. My project is to integrate this ultrasonic sensor to read the pingTravelTime so I can use this variable to get a target distance. However sensor is printing 0 on the serial monitor. I've different iterations but I'm stucked with this sensor. Thanks

thanks for your reply. I wired this sensor as normal wiring diagram thru arduino nano. The code works but its only printing zero to the serial monitor.
I want to use this variable from the "pingTravelTime" to measure distance. If I'm getting zero variable I can't use this variable to measure distance.
Below is another Arduino code uploaded to my Arduino Uno R4 and its still printing 0 and 0cm on the serial monitor.
I wired the vcc pin of the sensor to 5 volts, trigPin to pin 6, echoPin to pin 5 and ground pin to ground of Arduino.
I hope I done this reply to you ok.
Thanks

Here is another code I tried and it's printing 0 on the serial monitor.

`t#include <HCSR04.h>

int trigPin = 6;
int echoPin = 5;
int pingTravelTime;
int dt = 10;
int dt1 = 100; //for accuracy 100 microseconds delay rate recommended
int dt2 = 200;

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);

}

void loop() {
// establish variables for duration of the ping, and the distance result
  // in inches and centimeters:
  long duration, inches, cm;

digitalWrite(trigPin, LOW);
delayMicroseconds(dt);
digitalWrite(trigPin, HIGH);
delayMicroseconds(dt);
digitalWrite(trigPin, LOW);
pingTravelTime = pulseIn(echoPin, HIGH);
delayMicroseconds(dt1);
Serial.println(pingTravelTime);

// The same pin is used to read the signal from the PING))): a HIGH pulse
  // whose duration is the time (in microseconds) from the sending of the ping
  // to the reception of its echo off of an object.
    duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(dt2);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are 73.746
  // microseconds per inch (i.e. sound travels at 1130 feet per second).
  // This gives the distance travelled by the ping, outbound and return,
  // so we divide by 2 to get the distance of the obstacle.
  // See: https://www.parallax.com/package/ping-ultrasonic-distance-sensor-downloads/
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the object we
  // take half of the distance travelled.
  return microseconds / 29 / 2;
}

Hi TomGeorge,

Thanks for your help. I tried what you suggested and its still printing 0 on the serial monitor.
I want to use this variable "pingTravelTime" to measure distance so I can incorporate this to a robot car.
Thanks

Hi, @chito1623

Can you please post a copy of your circuit, a picture of a hand drawn circuit in jpg, png?
Hand drawn and photographed is perfectly acceptable.
Please include ALL hardware, power supplies, component names and pin labels.

Can you post some images of your project?
So we can see your component layout.

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

Hi Brazilino,

Thanks for your reply, I tried your modified code wired the sensor as vcc pin of sensor to 5 volts pin of arduino, trigPin of sensor to A0 of Arduino, echo pin of sensor to A1 of Arduino and ground of sensor to ground of Arduino.
It's printing 0 on the serial monitor. What numbers should be printing on the monitor?

Something between 118 and 23343. You can take a look by yourself at the simulation here:

https://wokwi.com/projects/407098178668363777

click on the image button. When the sim starts, click on the Sonar and change the values.

I think for now you should follow @TomGeorge 's advice and use a library to get the distance without worrying with manually triggering the sensor and doing the math.

Chito1623,
I've just tried your code from post #9.
It partially works.

It looks like you have got that got that code by combining two separate codes.

  • You trigger the trigPin
  • The echoPin generates a pulse
  • You measure the pulse width using pulseIn()
  • You print the 'pingTravelTime' - correct result
  • You then use pulseIn() again - but the pulse has already gone!
  • The serial monitor now prints zero for the distance in inches / centimetres

You can't use pulseIn() twice to measure the same pulse.

If you change that:

duration = pulseIn(echoPin, HIGH);  `

to:

duration = pingTravelTime;

you can use the initial (correct) results twice.

Screenshot 2024-08-24 123711

Sorry Tom George, I don't know how to paste a photo to this forum.
Thanks

When you reply, click on the upload button that I have highlighted below.

You can then navigate to whereabouts on your computer the photo is, and then add it.
Screenshot 2024-08-24 Upload

Do you have something in front of the sensor so it can get an echo?

Hi johnLincoln,

I tried what you suggested I'm still getting zero on the serial monitor.

Yes

Are you using a solderless breadboard to make connections?