PC Services


PC Services (Electronics)

Simple Echo Example for Ultrasonic Distance Sensor HC-SR04

Tel: 0118 946 3634

linked-in profile facebook profile

   The Company 
   Resources / Examples 
       Simple Echo Example 

Simple Example Sketch for Ultrasonic Range Sensing

Other Pages cover


This like most examples uses the function 'pulseIn', and sits in a loop getting results and putting them to the serial port. However unlike other examples, does the following -

  • Uses pulseIn and sets the optional TIMEOUT parameter that most do not use, to 30 ms, so the function will return with value of 0. The trouble is pulseIn can get stuck because the ECHO pin was already high and waits for the signal to go LOW then HIGH again.

    Default TIMEOUT value for pulseIn is one second so your programme could sit wasting time for a second before returning from this function.
  • Most examples poll the sensor very slowly usually twice a second, this example is set to poll the sensor 30 ms after the last reading has been converted
  • Most examples set the TRIG pin output for their Arduino to LOW everytime just before they set it HIGH then LOW again to create a pulse output, this is at best - poor programming at worst plain WRONG. If you have to do that because another part of the code might set it HIGH elsewhere, then there are serious issues elsewhere in your code, as you will have created TWO TRIG pulses in close succession. The standard Arduino sketch structure has a function called 'setup( )' where you set up pin modes AND default state. If you have a library class then when it is instantiated or initialised (begin) it should be setting the pin LOW there !!
  • Only the value is output to the serial port
  • Maths is kept at integer maths

This example exercises the sensor rapidly if you do not get steady readings for a stationary object, then if you have not altered the code at all, the most likely scenario is that your sensor has died or has bad components on it. See the Circuitry section for more information and possible remedies.

Back to top

Simple Echo Example Code

This example can be viewed below or download a zip file of example simple-echo.zip

Back to top

Read the comments at top of the code and the first section of constants (#define) for pin configuration and settings.

/* Ultrasonic distance sensor example Simple version Paul Carpenter, PC Services 24-Jan-2017 Uses HC-SR04 four pin ultrasonic sensor to continuously output distances found when in range (every second). Results output onto serial port at 115,200 baud Works on principle sound travels at 343.2 m/s in dry air at 20 deg C So time per cm is 29.137529 micro seconds /cm For round trip (there and back) 58.275058 micro seconds /cm In order to reduce code size and execution time values are kept as integers and factor of 58 to calculate distances */ /* Pin definitions */ #define echopin 4 #define trigpin 5 /* time between readings in ms On Arduino Mega readings belown 20ms interval could have residual echo issues */ #define INTERVAL 30 /* Timeout for distance sensing rather than 1 second */ #define MAX_ECHO 30000 /* Scale factor round trip micro seconds per cm */ #define SCALE_CM 58 /* calculated distance in centimetres */ unsigned long distance; /* time values to determine WHEN to do a ping */ unsigned long next_time, new_time; void setup( ) { next_time = INTERVAL; /* set time from reset */ Serial.begin( 115200 ); /* Configure pins and ensure trigger is OFF */ pinMode( trigpin, OUTPUT ); digitalWrite( trigpin, LOW ); // Set trig pin LOW here NOT later pinMode( echopin, INPUT ); /* Send signon message */ Serial.println( F( "PC Services - Simple Range test" ) ); } void loop( ) { /* check if to run this time */ new_time = millis( ); if( new_time >= next_time ) { digitalWrite( trigpin, HIGH ); delayMicroseconds( 10 ); digitalWrite( trigpin, LOW ); /* echo time in microseconds Maximum MAX_ECHO Minimum 0 (NO ECHO) Timeout for measurements set by MAX_ECHO define (constant) */ distance = pulseIn( echopin, HIGH, MAX_ECHO ); /* Calculate distance only for VALID readings 0 is no echo or timeout */ if( distance > 0 ) distance /= SCALE_CM; Serial.println( int( distance ) ); // Output distance in whole cm next_time = new_time + INTERVAL; // save next time to run this part of loop } /* Run other code here */ }

Back to top

Other Pages cover

Interested in something similar contact sales.

© 2017 onwards by PC Services, Reading UK Last Updated: 1st February 2017
If you encounter problems with this page please email your comments to webmaster