4 years, 6 months ago.

Ultrasonic HC SR04 Interface Issue with LPC1768 on m3pi

I am using the following code to interface hc sr-04 from sparkfun with LPC1768 mounted with m3pi bot. I have tried all the libraries available in the mbed handbooks and have even changed my ultrasonic sensor to check if the sensor is faulty, however, I am not able to get any readings from the sensor. I tried to block the receiver and see, and it does give a maximum distance reading(177cm corresponding to the timeout of 10ms). Apart from that, I am getting almost zero readings with a few correct readings here and there, maybe 3 to 4 readings in 5 minutes. Surprisingly, these random readings that I get sometimes are correct readings. (Similar behavior with two different sensors.)

#include "mbed.h"
#include "m3pi.h"
Serial pc(USBTX, USBRX); 
DigitalOut trigger(p6);
DigitalOut myled(LED1); //monitor trigger
DigitalOut myled2(LED2); //monitor echo
DigitalIn  echo(p7);
int distance = 0;
int correction = 0;
int timeout = 0;
Timer sonar, to;
int main()
//Loop to read Sonar distance values, scale, and print
    while(1) {
// trigger sonar to send a ping
        trigger = 0;
        myled = 1;
        myled2 = 0;
        trigger = 1;
        trigger = 0;
        myled = 0;
        while (echo==0 && sonar.read_ms()<10) {};
        while (echo==1 && sonar.read_ms()<10) {};
        distance = (sonar.read_us())/58.0;
        myled2 = 0;
        pc.printf(" %d cm \n\r",distance);

Please do help me out and let me know where I am going wrong.

2 Answers

3 years, 11 months ago.

Check if you have set the echo pin mode to "PullDown" which means it has zero value when there is no return pulse from the sensor.

3 years, 10 months ago.

Check this device operation manual and make sure you have the right hardware connections. From what I see you're not doing it right. Read the manual. If you don't get it right then come back and we'll make it work.