RPi: HC-SR04 Ultrasonic Sensor mini-project

In an almost biblical revelation, I have found it IS indeed possible to post source code in a proper fashion on WordPress, making a virtual mockery of my Pebble SDK Tutorial pages, which I might update, but not for now. The code segments are available in source links in each post.

So, what better reason to make a new post using this newly discovered feature than to write about my latest Raspberry Pi escapade. I have a cheap HC-SR04 ultrasonic sensor that I used with an Ultrasonic library with my Arduino. Having since obtained a Pi, why not have it work with this new piece of kit?

After observing the timing requirements, it seemed simple enough to replicate that behavior with a short C program, shown below in all it’s copyable glory!

#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>

#define TRUE 1

#define TRIG 5
#define ECHO 6

void setup() {
        wiringPiSetup();
        pinMode(TRIG, OUTPUT);
        pinMode(ECHO, INPUT);

        //TRIG pin must start LOW
        digitalWrite(TRIG, LOW);
        delay(30);
}

int getCM() {
        //Send trig pulse
        digitalWrite(TRIG, HIGH);
        delayMicroseconds(20);
        digitalWrite(TRIG, LOW);

        //Wait for echo start
        while(digitalRead(ECHO) == LOW);

        //Wait for echo end
        long startTime = micros();
        while(digitalRead(ECHO) == HIGH);
        long travelTime = micros() - startTime;

        //Get distance in cm
        int distance = travelTime / 58;

        return distance;
}

int main(void) {
        setup();

        printf("Distance: %dcm\n", getCM());

        return 0;
}

Which results in this output:

ultrasonic

So now I know the distance to the ceiling!

Advertisements
29 comments
  1. 23 said:

    how distance = travelTime / 58 ?

    • bonsitm said:

      Hi 23,

      The speed of sound is 340 m/s or 29 microseconds per centimeter. Taking half the total distance (there and back) we can use the divisor 58.

  2. jestrada said:

    Thanks for the code…I am doing a project to control two DC motors with three different ping sensors (HC-SR04). I prefer C over python and this gives me a good reference!

  3. amba said:

    hey
    i used this code but it gives error an error(i used geany for compilation and wiringPi library)
    the error is
    sensor.c:15:2:error:expected ‘;’ befor ‘}’ token………..compilation failed;
    but when i add ‘:’after delayMicreseconds(30);
    it gives bundle of error like
    undefined reference to ‘digitalRead’
    undefined reference to wiringPisetup
    undefined reference to pinMode
    etc
    please help

    • bonsitm said:

      Hi. This error means you are missing a semi-colon (‘;’, not ‘:’) at the end of the line indicated. By adding an incorrect ‘:’, further errors will (and have, it seems) result.

      Simply place the correct character at the end of the line (or take a fresh copy from the post) and it should compile.

      Chris

      • amba said:

        thanks
        i placed characters on right places but now it gives bundle of errors, i mentioned them below
        undefined reference to ‘wiringPisetup’
        undefined reference to ‘pinMode’
        undefined reference to ‘digitalwrite’
        undefined reference to ‘delay’
        undefined reference to ‘getCM’
        undefined reference to ‘delayMicroseconds’
        undefined reference to ‘digitalRead’
        undefined reference to ‘micros’
        i would be thankful to you if you help me to eliminate these errors

      • bonsitm said:

        Amba, are you sure you have the correct raspberry pi libraries installed? Send me a link your code file so I can read it.

      • amba said:

        i had installed noobs using this link
        http://www.raspberrypi.org/downloads/
        then i installed geany using this link
        http://www.geany.org/Download/Releases .(full installer version)
        and after it wiringPi library from here
        https://git.drogon.net/?p=wiringPi;a=summary

        i would like to mention the hello word program works properly using c template but i am unable to run any other program for my ultrasonic sensor
        will you please tell me what’s wrong with my program or path as its 2 months i am trying to measure distance but failed

      • bonsitm said:

        My Pi uses Raspbian and I used nano to write the code, so I can’t offer any help with either noobs or geany, but hopefully there are similar enough to not cause problems, but I can’t rule that out.

        Also, setting up wiringPi is not as simply as extracting the files, unfortunately. Double check this here: http://wiringpi.com/download-and-install/

        Once again, may I have a link to a place where I can read your code you are trying to compile?

      • amba said:

        ok its the link from where i got the code
        https://ninedof.wordpress.com/2013/07/16/rpi-hc-sr04-ultrasonic-sensor-mini-project/comment-page-1/#comment-710
        and i had just not extracted files .. i download it from provided link and then using winscp i transfered files to the raspberryPI
        even after it i tested my pi using these codes
        tar xfz wiringPi-477f856.tar.gz
        cd wiringPi-477f856
        ./build
        and then test it by
        gpio -v
        gpio readall
        it runs smoothly
        i faced problem while using above code

      • bonsitm said:

        Ok. Perhaps there has been a change in wiringPi. I will re-compile the code on my blog when I next get a chance.

      • amba said:

        should i install the new version of wiring pi or can you please give me your link or which version you have installed

  4. amba said:

    now i am trying to compile the above code using c template in geany and i get above errors mentioned in previous message

  5. Sayeed said:

    bro, I tried it but code blocks on my RPI 2 doesn’t find the header file wiringpi.h . what can I do now?

    • bonsitm said:

      You need to first install the WiringPi library, and make the header available to gcc through PATH.

  6. gabriel said:

    thank you! very acurrate and usefull!

  7. Nitin Patil said:

    Thanks for code….
    But its not running…it stuck their when i run program means show nothing => sudo ./a.out
    please help me out

  8. When compiling you need to include the wiringpi like so:sudo gcc -o distance distance.c -lwiringPi
    This should compile for you, however I found the code doesn’t return anything, it seems to be getting stuck around the 2 while loops. My sensor is working as ive tried same using python, its slow but at least its working. I am new to this myself and really want to code it all in C simply for the speed.

  9. john said:

    Thanks for the code, it was usefull.
    I have a question why do you use a delay of 30 and a delayMicroseconds of 30?

    • bonsitm said:

      This is to ensure that the pulses are of the correct length when changing pin logic levels.

  10. madan said:

    while(digitalRead(ECHO) == HIGH);
    my echo is not high.
    so infinite while.
    I think the problem is my echo pin.
    your pins are 5 and 6.
    but my pin 6 is ground.
    help please.

    • Alex-I said:

      Hi Madam,
      wiringPi library have a different pin numbering.
      It’s a little bit confusing, but you can google for wiringPi pins or look here: https://pinout.xyz/ .It help me a lot.
      (i hope it’s ok i put the link.If not, please delete the link).
      Sorry for my english. 🙂

      • madan said:

        Thank you very much. Good english by the way.

  11. Nyron said:

    Thanks man it works. I just needed to comment out the #define true and then include wiringPiSetupGpio();

  12. miera said:

    can i get the structure of a circuit diagram for this code?

  13. Hello.
    After a long long journey, finally i can compile this code and return “Compilation finished successfully”.
    I’m so happy!

    But, when i run the program, it return nothing.
    Can you help me? Did i missed something?

    Thank you for replying! 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: