Ultrasonic Distance Detector (HC-SR04)


I have a raspberry Pi that has the particle-agent installed, and i have been trying to get the HC-SR04 to work on. i have been following this guide by @rocksetta (Ultrasonic range finder simple code).

//using Ultrasonic Range Finder from Robotshop

unsigned long duration;

void setup()
                           // ultrasonic range finder Robotshop RB-lte-54
                           // GND pin goes to ground
    pinMode(D11, INPUT);    // echo
    pinMode(D10, OUTPUT);   // Trig
                           // VCC pin goes to VIN on the photon

void loop(){
        delay(1000);// even cicuits need a break
        digitalWrite(D10, HIGH);  
        digitalWrite(D10, LOW);  

        duration = pulseIn(D11, LOW);   // how long until a reply?
                                        // a blocking call so may wait a few seconds

The output from this code always returns “0” no matter what i put, i even tried delayMicroseconds(); instead of delay but still no results. i tested the code on an Arduino and the sensor works great, but on the particle-agent it does not. Am I doing something wrong? I’ve tried everything that i can think of, not sure whats next.

Trigger and return values from python script

Have you tried using the library function HC_SR04? Looking at the code snippet the pulse length seems long 1000 microSeconds whereas the library uses 10 microSeconds and the duration calculation is returning a distance - maybe what you want rather than duration of pulse!


Hey! Thanks for the reply @armor , i have also tried it, i had the same results. and i did try shorter time periods :confused:


The problem is that pulseIn is not supported on the Raspberry Pi. You’ll need to implement it by hand by polling the pin for change and measuring times.


@rickkas7 That’s good point, which I wasn’t sure about - however the library HC_SR04 does not use pulseIn().

@karam Have you tried voltage splitting the echo pin as recommended (I am not certain about RPi - photon does not work unless voltage split using 2 470ohm resistors. Also, are you sure that the pins are connected correctly to the RPi header (and is the pin compatible with digital I/O). Software wise, pinSetFast() and pinReadFast() are more appropriate for fast switching and reading (not sure if these are implemented in RPi).


@armor hey! Sorry about the later reply, but I have tried other methods including the ones stated above, and still no results. I was thinking making particle trigger a python script and get the results back, not really sure how to make it do that yet, any suggestions or tips on how that would work? I have found the source where you can call a function and it will return a value back. I did that using the command that gives you the cpu temp back, but couldn’t get it to run my own script.