Here is code from RPi: HC-SR04 Ultrasonic Sensor mini-project

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

#define TRUE 1

#define TRIG 5
#define ECHO 6

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

        //TRIG pin must start LOW
        digitalWrite(TRIG, LOW);

int getCM() 
        //Send trig pulse
        digitalWrite(TRIG, HIGH);
        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) 

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

        return 0;

While I didn't get any error but I don't get any output.

I used some debugging, like using printf() in between statements to check where it gets stuck, so I found that it got stuck at this statement:

while(digitalRead(ECHO) == LOW);

Please help me out why the code is getting stuck there.

  • 2
    If it's sticking at that line, Pin 6 (ECHO) is never going low - check your wiring, check the sonar device with a voltmeter or scope, or write some test routines outside of this code - it looks like the pin should drop low soon after TRIG goes low. If you have an Arduino, they're great for testing this sort of gadget. – Mark Williams Jul 19 '15 at 21:24
  • 2
    @MarkWilliams typo, never going high. raspberrypi.org/forums/viewtopic.php?f=37&t=79520 – joan Jul 20 '15 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.