2 years, 6 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./media/uploads/Alllen/---ieq1s3v8xg--bpb--3kl.png

1 Answer

2 years, 6 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();

}

Accepted Answer

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 gao yuan 17 May 2019