Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 9 months ago.
Ultrasonic HC-SR04 returns zero distance range
Hello,
I was attempting to interface ultrasonic sensor HC-SR04 with mbed (LPC1768) but the distance reading is always zero. I tried using pin 6 and pin 7 (trigger, echo) and then changed to pin 27, pin 28 (trigger, echo) but without any valid reading. It's always zero. Please can someone help?
Code:
- include "mbed.h"
- include "hcsr04.h"
HCSR04 usensor(p27,p28);trig pin,echo pin Serial pc(USBTX, USBRX); unsigned int dist; int main() {
while(1) { usensor.start(); wait_ms(500); dist=usensor.get_dist_cm(); pc.printf("Distance = %d cm\n",dist);
} }
2 Answers
9 years, 8 months ago.
Hello. My first (detailed reply got killed by the crazy online editor which is obviously buggy).
Here is the summary:
a) you are using open drain pins (p27 & p28 = open drain). So the same pins cannot supply a logic high without the use of external pull-ups.
b) move the port pins to another pair which are confirmed to be general purpose I/O - you can view the electrical properties from the NXP datasheet for the same microcontroller.
Here is an article on known to be working pins:
http://developer.mbed.org/users/prabhuvd/code/HCSR04/wiki/Homepage#schematic
Hope this helps ! Write back if still stuck and then will make an effort to locate the same mbed board and sensor (somewhere in this building) to replicate the project.
Kumar
the solution to the sensor being stuck at zero in Arduino is in this link. Maybe it will give you an idea, you seem to have a similar probem. its the 2. post, by docdoc. You will need the NewPing library which is far better. Basically when stuck at zero, the echo pin is turned to output, given a low pulse then turned to input.
A working code:
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
delay(50);
unsigned int uS = sonar.ping();
pinMode(ECHO_PIN,OUTPUT);
digitalWrite(ECHO_PIN,LOW);
pinMode(ECHO_PIN,INPUT);
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
}
link: http://forum.arduino.cc/index.php?topic=55119.15
NewPing link: http://playground.arduino.cc/Code/NewPing
posted by mehmet zahit baş 22 Nov 2015Thanks a lot for your answer Mehmet !!
posted by Lakshmanan Gopalakrishnan 23 Nov 2015