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.
4 years, 11 months ago.
ultrasonic sensor
Could any one help me with some questions? thanks!! I want to measure distance using an ultrasonic sensor and print the measurement on LCD. I have finished the code but it has some problems and the most serious one is that it cannot return a number from the sensor. I think LCD does not have problems because it can print the words "the distance is". Below is my code.
1 Answer
4 years, 11 months ago.
Why are you using analog pins for digital IO? I'm not sure why you get nothing, you should get 0 all of the time since an analog input is very rarely going to be 0 or 1 exactly.
Also please use
<<code>> your code <</code>>
to include code rather than posting an image. I can't copy and paste an image to update your code
Rather than using analog IO and infinite while loops that could cause latchup I'd use an interrupt to detect the critical edge of the signal.
InterruptIn echoIn(<pin>); // interrupt in DigitalOut triggerOut(<pin>); // digital control output Timer echoTime; volatile uint32_t pulseLen; void onInterrupt(void) { pulseLen = echoTime.read_us(); // on an interrupt record the time } float distance() { pulseLen = 0; echoTime.stop(); echoTime.reset(); trigOut = 1; // create a trigger pulse wait_us(50); trigOut = 0; echoTime.start(); // start the timer while ((echoTime < 1) && (pulseLen==0)) // wait until the interrupt triggers or for a maximum of 1 second. wait_us(50); if (pulseLen==0) // nothing after 1 second return 99999.99f; return pusleLen*34.0f/200.0f; } int main() { echoIn.fall(&onInterrupt); // configure the interrupt to trigger on a falling edge.. a=distance(); }
Thank you for your explanation and your code! I'm sorry for the inconvenience caused by the image. This is my first time to ask question here and I'll correct it next time. Now I have finished the project, and it works well with the help of your code. From the experiment I noticed the problems of my foundation, and I need to work more on it. I learned a lot from the question. Thank you once again .
posted by 17 May 2019