Ethan Hall
/
UltraSonicRangeDetector
Code to use a MaxSonar for range detection.
main.cpp@0:753612ff63ad, 2011-09-18 (annotated)
- Committer:
- ethankhall
- Date:
- Sun Sep 18 16:35:45 2011 +0000
- Revision:
- 0:753612ff63ad
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
ethankhall | 0:753612ff63ad | 1 | #include "mbed.h" |
ethankhall | 0:753612ff63ad | 2 | |
ethankhall | 0:753612ff63ad | 3 | /** |
ethankhall | 0:753612ff63ad | 4 | This source code is used to connect a MaxSonar detector. It is written to allow multiple sonar's. |
ethankhall | 0:753612ff63ad | 5 | If you want the sonar to constantly poll constantly either: don't attach the pin, or delete the code relating to 'Enable' |
ethankhall | 0:753612ff63ad | 6 | |
ethankhall | 0:753612ff63ad | 7 | This code is public domain. |
ethankhall | 0:753612ff63ad | 8 | **/ |
ethankhall | 0:753612ff63ad | 9 | |
ethankhall | 0:753612ff63ad | 10 | AnalogIn Sensor(p20); //Analog port that is connected to the MaxSonar range detector |
ethankhall | 0:753612ff63ad | 11 | DigitalOut Enable(p18); //Remove this if you want a constant poll |
ethankhall | 0:753612ff63ad | 12 | DigitalOut led(LED1); //led, useful to see when the sonar is polling |
ethankhall | 0:753612ff63ad | 13 | Serial serialPort(USBTX, USBRX); //To talk back to your computer |
ethankhall | 0:753612ff63ad | 14 | |
ethankhall | 0:753612ff63ad | 15 | int main() { |
ethankhall | 0:753612ff63ad | 16 | float adc, volts, in; |
ethankhall | 0:753612ff63ad | 17 | |
ethankhall | 0:753612ff63ad | 18 | while (1) { |
ethankhall | 0:753612ff63ad | 19 | Enable = 1; //Enable the sonar |
ethankhall | 0:753612ff63ad | 20 | led = 1; //Turn the LED on to show let the user know its working |
ethankhall | 0:753612ff63ad | 21 | wait_us(25);//Wait 20uS + 5uS safety margin |
ethankhall | 0:753612ff63ad | 22 | adc = Sensor.read(); //Read the sensor value |
ethankhall | 0:753612ff63ad | 23 | Enable = 0; //Disable the sonar |
ethankhall | 0:753612ff63ad | 24 | led = 0; //Turn the LED off |
ethankhall | 0:753612ff63ad | 25 | volts = ( adc * 3.3 ); // convert to volts |
ethankhall | 0:753612ff63ad | 26 | in = volts / 0.0032 * 0.3937; // 3.3V supply: 3.2mV per cm * CM -> IN conversion factor |
ethankhall | 0:753612ff63ad | 27 | |
ethankhall | 0:753612ff63ad | 28 | serialPort.printf("%8.5f adc %8.5fV %8.2f\"\n", adc, volts, in); |
ethankhall | 0:753612ff63ad | 29 | |
ethankhall | 0:753612ff63ad | 30 | wait(0.5); |
ethankhall | 0:753612ff63ad | 31 | } |
ethankhall | 0:753612ff63ad | 32 | } |