Kildekode

Dependencies:   mbed

Fork of Team5_kode by Kim Nielsen

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers HCSR04.cpp Source File

HCSR04.cpp

00001 /*
00002 Dette er cpp filen for ultralydssensoren
00003 */
00004 #include "mbed.h"
00005 #include "HCSR04.h"
00006 
00007 HCSR04::HCSR04(PinName echoPin, PinName triggerPin) : echo(echoPin), trigger(triggerPin) {
00008     init();
00009 }
00010 
00011 void HCSR04::init() {
00012     /** configure the rising edge to start the timer */
00013     echo.rise(this, &HCSR04::startTimer);
00014     
00015     /** configure the falling edge to stop the timer */
00016     echo.fall(this, &HCSR04::stopTimer);
00017     
00018     distance = -1;      // initial distance
00019     minDistance = 2;
00020     maxDistance = 400;
00021 }
00022 
00023 void HCSR04::startTimer() {
00024     timer.start(); // start the timer
00025 }
00026 
00027 void HCSR04::stopTimer() {
00028     timer.stop(); // stop the timer
00029 }
00030 
00031 void HCSR04::startMeasurement() {
00032     trigger = 1;
00033     wait_us(10);
00034     trigger = 0;
00035     wait_ms(25); // just enough time to measure 400 cm
00036     timer.stop(); // just in case echo fall did not occur
00037     distance = timer.read() * 1e6 / 58;
00038     if (distance < minDistance)
00039         distance = minDistance;
00040     if (distance > maxDistance)
00041         distance = maxDistance;
00042     timer.reset();
00043 }
00044 
00045 float HCSR04::getDistance_cm() {
00046     startMeasurement();
00047     return distance;
00048 }
00049 
00050 float HCSR04::getDistance_mm() {
00051     startMeasurement();
00052     return distance * 10;
00053 }
00054 
00055 void HCSR04::setRanges(float minRange, float maxRange) {
00056     if (minRange < maxRange) {
00057         if (minRange >= 2) 
00058             minDistance = minRange;
00059         if (maxRange <= 400)
00060             maxDistance = maxRange;
00061     }
00062 }
00063 
00064 float HCSR04::getMinRange() {
00065     return minDistance;
00066 }
00067 
00068 float HCSR04::getMaxRange() {
00069     return maxDistance;
00070 }