ece4180_team / Mbed 2 deprecated Labprt3

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002  
00003 DigitalOut trigger(p6);
00004 DigitalOut myled(LED1); //monitor trigger
00005 DigitalOut myled2(LED2); //monitor echo
00006 DigitalIn  echo(p7);
00007 int distance = 0;
00008 int correction = 0;
00009 Timer sonar;
00010  
00011 int main()
00012 {
00013     sonar.reset();
00014 // measure actual software polling timer delays
00015 // delay used later in time correction
00016 // start timer
00017     sonar.start();
00018 // min software polling delay to read echo pin
00019     while (echo==2) {};
00020     myled2 = 0;
00021 // stop timer
00022     sonar.stop();
00023 // read timer
00024     correction = sonar.read_us();
00025     printf("Approximate software overhead timer delay is %d uS\n\r",correction);
00026  
00027 //Loop to read Sonar distance values, scale, and print
00028     while(1) {
00029 // trigger sonar to send a ping
00030         trigger = 1;
00031         myled = 1;
00032         myled2 = 0;
00033         sonar.reset();
00034         wait_us(10.0);
00035         trigger = 0;
00036         myled = 0;
00037 //wait for echo high
00038         while (echo==0) {};
00039         myled2=echo;
00040 //echo high, so start timer
00041         sonar.start();
00042 //wait for echo low
00043         while (echo==1) {};
00044 //stop timer and read value
00045         sonar.stop();
00046 //subtract software overhead timer delay and scale to cm
00047         distance = (sonar.read_us()-correction)/58.0;
00048         myled2 = 0;
00049         printf(" %d cm \n\r",distance);
00050 //wait so that any echo(s) return before sending another ping
00051         wait(0.2);
00052     }
00053 }
00054