Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: HC_SR04_Ultrasonic_Library mbed
Fork of Nucleo_UltrasonicHelloWorld by
main.cpp
00001 #include "mbed.h" 00002 00003 DigitalOut trigger(p13); 00004 DigitalOut myled(LED1); //monitor trigger 00005 DigitalOut myled2(LED2); //monitor echo 00006 DigitalOut myled3(LED3); 00007 DigitalOut myled4(LED4); 00008 DigitalIn echo(p14); 00009 int distance = 0; 00010 int correction = 0; 00011 Timer sonar; 00012 00013 int main() 00014 { 00015 sonar.reset(); 00016 // measure actual software polling timer delays 00017 // delay used later in time correction 00018 // start timer 00019 sonar.start(); 00020 // min software polling delay to read echo pin 00021 while (echo==2) {}; 00022 myled2 = 0; 00023 // stop timer 00024 sonar.stop(); 00025 // read timer 00026 correction = sonar.read_us(); 00027 printf("Approximate software overhead timer delay is %d uS\n\r",correction); 00028 00029 //Loop to read Sonar distance values, scale, and print 00030 while(1) { 00031 // trigger sonar to send a ping 00032 trigger = 1; 00033 myled = 1; 00034 myled2 = 0; 00035 sonar.reset(); 00036 wait_us(10.0); 00037 trigger = 0; 00038 myled = 0; 00039 //wait for echo high 00040 while (echo==0) {}; 00041 myled2=echo; 00042 //echo high, so start timer 00043 sonar.start(); 00044 //wait for echo low 00045 while (echo==1) {}; 00046 //stop timer and read value 00047 sonar.stop(); 00048 //subtract software overhead timer delay and scale to cm 00049 distance = (sonar.read_us()-correction)/58.0; 00050 myled2 = 0; 00051 printf(" %d cm \n\r",distance); 00052 00053 if (distance<10) { 00054 myled3= 1; 00055 } 00056 if (distance>=10) { 00057 myled4= 1; 00058 } 00059 00060 00061 //wait so that any echo(s) return before sending another ping 00062 wait(0.2); 00063 myled3 = myled4 = 0; 00064 } 00065 }
Generated on Sat Aug 13 2022 01:00:44 by
1.7.2
