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.
main.cpp
00001 #include "mbed.h" 00002 00003 Serial pc(USBTX,USBRX); 00004 00005 DigitalInOut pingPin(p18); 00006 00007 Timer tmr; 00008 00009 long microsecondsToInches(long microseconds); 00010 long microsecondsToCentimeters(long microseconds); 00011 00012 int main() { 00013 while (1) { 00014 // establish variables for duration of the ping, 00015 // and the distance result in inches and centimeters: 00016 long duration, inches, cm; 00017 00018 // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. 00019 // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: 00020 pingPin.output(); 00021 pingPin = 0; 00022 wait_us(2); 00023 pingPin = 1; 00024 wait_us(5); 00025 pingPin = 0; 00026 00027 // The same pin is used to read the signal from the PING))): a HIGH 00028 // pulse whose duration is the time (in microseconds) from the sending 00029 // of the ping to the reception of its echo off of an object. 00030 pingPin.input(); 00031 00032 // pulseIn 00033 while (!pingPin); // wait for high 00034 tmr.start(); 00035 while (pingPin); // wait for low 00036 duration = tmr.read_us(); 00037 00038 // convert the time into a distance 00039 inches = microsecondsToInches(duration); 00040 cm = microsecondsToCentimeters(duration); 00041 00042 pc.printf("in=%4d, cm=%4d\n", inches, cm); 00043 wait_ms(100); 00044 } 00045 } 00046 00047 long microsecondsToInches(long microseconds) { 00048 // According to Parallax's datasheet for the PING))), there are 00049 // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per 00050 // second). This gives the distance travelled by the ping, outbound 00051 // and return, so we divide by 2 to get the distance of the obstacle. 00052 // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf 00053 return microseconds / 74 / 2; 00054 } 00055 00056 long microsecondsToCentimeters(long microseconds) { 00057 // The speed of sound is 340 m/s or 29 microseconds per centimeter. 00058 // The ping travels out and back, so to find the distance of the 00059 // object we take half of the distance travelled. 00060 return microseconds / 29 / 2; 00061 }
Generated on Wed Aug 31 2022 05:21:19 by
1.7.2