HC-SR04 Ultrasonic Sensor on PIC

Hcsr04 Banner
HC-SR04 is a very common ultrasonic sensor and it is normally found in Arduino kits or projects. The library for this sensor is widely available for the Arduino platform but not for PIC.


I’ve been asked to help to write a simple PIC code to interface with the ultrasonic sensor.


It’s actually very simple by referring to the timing diagram.


Connect the Trigger pin to an output and the Echo pin to an input. Just output a 10us pulse on the trigger pin and wait for the feedback on the echo pin.

The pulse width of the echo pin will determine the distance. The longer the pulse width, the further the object is. I’m using the PIC’s built-in timer to time the duration of the pulse width.

The code is written for the Hi-Tech C Lite compiler on MPLAB X.


The schematic.


Here is a video demo 🙂


Print Friendly
  1. sonali02-15-2018

    Respected Sir l am doing a project ultrasonic radar system , I want help for coding ( base on pic18f microntroller ) .plz help mii

  2. dedektör02-02-2018

    nice work. I wonder how this system can be applied to RF signals.

  3. TobiasX08-10-2017

    Hello admin i see you don’t monetize your blog. You can earn extra
    bucks easily, search on youtube for: how to earn selling articles

  4. Harvy02-19-2017

    //can someone tell me what is wrong with my code? i only see zeros in my serial monitor .

    int vals[10];
    unsigned int distance = 0;
    char txt[20];
    void sendPulse(void);
    unsigned int readUltrasonic(void);

    void main()


    while(1) {
    distance = readUltrasonic()/1.7;

    void sendPulse(void) {
    RB0_bit = 1;
    RB0_bit = 0;

    unsigned int readUltrasonic(void){
    unsigned int time = 0;

    while(1) { if(RB4==0) { break; } }

    while(1) {
    TMR0L = 0;
    time = TMR0L;
    return time;


  5. Ardnax sunev05-31-2016

    Can i ask for the library of ultrasonic sensor using pic?

  6. aim06-13-2015

    u said in the post u are using high tech c lite compiler but now i see your comment is xc8 which one is true??

  7. Trust05-10-2015

    thank you so much for the effort to help us learn. can you assist me with the code for hc-sr04 sensor and PIC16F877A in MikroC. i have a project that is due and i need this part to work. i am using 20MHz crystal.

  8. aravindh03-23-2015

    sir,we need coding for hcsr04 interfacing with pic16f877a for tank level controller.tank height of 13cm

  9. sathya03-23-2015

    sir can u give me a code for interfacing the pic16f877a with hcsr04 without lcd display……

  10. vignesh03-23-2015

    sir,we are doing project with ultrasonic sensor[hcsr04] for water level controller.i need coding to trigger the ultrasonic sensor without lcd display….pls help us….

  11. yasir12-05-2014

    plz any body help me.i want to make a small project using ultasonic hrs04 with OP AMP not any microcontroller.which give output in form of teo led blue and red.when ti are close then it turn red and when it largge range then blue.

  12. yasir12-05-2014

    plz any body help me.i want to make a small project using ultasonic hrs04 with OP AMP not any microcontroller.which give output in form of teo led blue and red.when ti are close then it turn red and when it largge range then blue.

  13. pavan kumar11-09-2014

    hi sir.thank you so much for the code and set up.it works well.but the max dist(im getting) shown is only 150 cm.but the rangeof hc-sr04 is supposed to be 2-400cm right?im using pic 16f877a with same set up.only using 20mhz crystal instead of 16 mhz crystal…could you please help me!!

    • waihung11-11-2014

      You’re welcome.

      Try to read the raw ADC values instead. In my code I have translated it into cm.
      Have a look at the raw values and try to figure out how to scale it to the max distance of 400cm.

  14. Khai_electronic08-18-2014

    sir can you show how to make that circuit in isis which..i be grateful if u could reply that

  15. vel07-04-2014

    Does anyone have HEX file for this code please?

  16. Jonathan06-19-2014

    Hola muy buen trabajo, solo quisiera saber como compilarlo en el MPLAB X gracias.

  17. mohammed05-22-2014

    hi , can you give me the hex file please , I will very very very very very thankful .

  18. Dalia04-25-2014

    amazing work sir .. hope the best for you
    I just want to ask about which file of these files i’ll burn on the pic

  19. ramones04-21-2014

    hi there,

    glad to found your project interfacing between PIC and Ultrasonic sensor.But could you show me how to use this code for assembly language?

    Thank you

    • Wai Hung04-22-2014

      I can’t help you with that unfortunately. Assembly language is too time consuming.

    • http://www./01-17-2017

      Oh. I got V. Brown in the Rice deal, too. That makes it better, right? I appreciate the banter though guys. I knew I’d get ripped. I’d be on board with the ripping. In the future, I’ll keep my trades from “that league” to myself. lol…VN:F [1.9.21_1169](from 3 votes)

    • That’s really shrewd! Good to see the logic set out so well.

    • http://www./03-01-2017

      No question this is the place to get this info, thanks y’all.

    • Could I possibly repost this to one of our sites with this subject? I’d link back to the authentic, of study course. Let me personally know by simply email everything you think?

  20. Houssam04-02-2014

    Nice work.
    just a question how you calculate the distance? on the code it shows the number of counts d=(TMR0)/1.7 the results in cm how you get this?
    Distance=(velocity of sound)*(time delay)/2, with velocity =340m/s (at 20 degree Celsius), and what is the duration of the timer since it operates on 16MHz crystal is it 1/16microsecond per unit (in timer TMR0) ?.
    Thank you

    • Houssam04-03-2014

      Got it!..
      1/[(Fosc/4)/prescaler=128]*340m/s/2=1.8 instead of 1.7

      • Wai Hung04-06-2014

        Sorry for the late reply. Actually the value obtained from the PIC is a rough estimate of distance, so I just use 1.7 from trial and error. I used a ruler to measure the real distance to compare what I got from the PIC.

      • Personally I think the Tenerians shouldve been more healthier than the Kiffians. Fish and a farming guaranteed higher grade protein and continuous supply of nourishment on daily basis. Hunting large game is never a sure thing and wont exactly turn you into a superman either.

  21. Sourav03-30-2014

    Sir I am working on a project which deals with PIC18F46k22..Sir could u help me out to interface the HC SR-04 Ultrasonic sensor with PIC18F46k22 with its code? It’s urgent, kindly help me out.

  22. Kevin Lim03-20-2014

    Another thing sir is… the sensor need around 10us of delay to work.. what will happened if supplied with 16us of delay?

    • Wai Hung03-21-2014

      I think it will work but it will overlap with the echo signal.

  23. Kevin Lim03-18-2014

    Hello sir, just received my HC-SR04 but the PIC still not arrived.. I want to know how can I test it if the unit is not faulty? can i just supply a voltage to the trigger pin and vcc while grounding the gnd???

    • Wai Hung03-18-2014

      You can power the sensor but the output pulses are so fast that you cannot see it by just putting an LED.
      However you can use an oscilloscope and set it to trigger on positive edge while measuring the echo pin.
      Of course you’ll need a tiny pulse on the trigger pin. I think a push button will do.

  24. hystrix03-11-2014

    sir,,i want to ask ,if i use pic 16f877,which one should i change on the coding?what is the different between this two types of pic?

    • waihung03-16-2014

      I believe they’re similar. Try to upload the same code and see what happens.
      I think it should work just fine.

      • hystrix03-17-2014

        thanks sir i will..

  25. DELNA03-11-2014


    • waihung03-16-2014

      The code can be downloaded above.
      It’s written in MPLAB X and using the XC8 Compiler.
      If you’re using another compiler you’ll have to convert the code yourself.

  26. Kevin Lim03-04-2014

    Hello sir,

    May I know what crystal did you used on the project?

    • Wai Hung03-05-2014


  27. yogita gangurde02-16-2014

    sir ,i am unable to find the code given in this article can u mail it to me.

    • Wai Hung02-17-2014

      Click on the Download link above. It’s a RAR file, use WinRar to extract it.
      This code is for MPLAB X. It’s an entire folder filled with random files and the code is in it (newmain.c).
      There is also a header file there for the LCD.
      If I were to send it to your e-mail the attachment will be like 20 files.

      • rahuf03-02-2014

        sir can u give me a code for interfacing the pic16f877a with hcsr04 please..its urgent

  28. yogita gangurde02-15-2014

    respected sir/mam,
    i am doing a project based on ultrasonic sensor .your this article is really very helpful for me.
    i need your help.in our project we have to interface four sensors like this.i will be very thankful to you if u guide me about interfacing.i would also like to refer your code.thank u..

    • Wai Hung02-15-2014

      Just make 4 different copies of the sendPulse() and readUltrasonic() functions and change to the corresponding pins of your sensors. Remember Trigger pin should be an output while the Echo pin should be an input. Set the corresponding TRIS registers also.

Leave a Reply to Kevin Lim Click here to cancel reply.