A distance measurement class using ultrasonic sensor HC-SR04.

Dependents:   Esercitazione4_4 HC-SR04 Group10_slave Oled_Gus ... more

The purpose of this library is to encourage students to develope their own classes. Instructions how to follow the development of this library for ultrasonic distance measurement are given here.

Committer:
tbjazic
Date:
Sun Dec 06 15:13:54 2015 +0000
Revision:
3:9a7899cf5e3a
Parent:
0:8871082486ac
Child:
4:aae70f15357f
Limited distance range added.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
tbjazic 0:8871082486ac 1 #include "mbed.h"
tbjazic 0:8871082486ac 2 #include "HCSR04.h"
tbjazic 0:8871082486ac 3
tbjazic 0:8871082486ac 4 HCSR04::HCSR04(PinName echoPin, PinName triggerPin) : echo(echoPin), trigger(triggerPin) {
tbjazic 0:8871082486ac 5 init();
tbjazic 0:8871082486ac 6 }
tbjazic 0:8871082486ac 7
tbjazic 0:8871082486ac 8 void HCSR04::init() {
tbjazic 0:8871082486ac 9 /** configure the rising edge to start the timer */
tbjazic 0:8871082486ac 10 echo.rise(this, &HCSR04::startTimer);
tbjazic 0:8871082486ac 11
tbjazic 0:8871082486ac 12 /** configure the falling edge to stop the timer */
tbjazic 0:8871082486ac 13 echo.fall(this, &HCSR04::stopTimer);
tbjazic 0:8871082486ac 14
tbjazic 3:9a7899cf5e3a 15 distance = -1; // initial distance
tbjazic 3:9a7899cf5e3a 16 minDistance = 4;
tbjazic 3:9a7899cf5e3a 17 maxDistance = 400;
tbjazic 0:8871082486ac 18 }
tbjazic 0:8871082486ac 19
tbjazic 0:8871082486ac 20 void HCSR04::startTimer() {
tbjazic 0:8871082486ac 21 timer.start(); // start the timer
tbjazic 0:8871082486ac 22 }
tbjazic 0:8871082486ac 23
tbjazic 0:8871082486ac 24 void HCSR04::stopTimer() {
tbjazic 0:8871082486ac 25 timer.stop(); // stop the timer
tbjazic 0:8871082486ac 26 }
tbjazic 0:8871082486ac 27
tbjazic 0:8871082486ac 28 void HCSR04::startMeasurement() {
tbjazic 0:8871082486ac 29 trigger = 1;
tbjazic 0:8871082486ac 30 wait_us(10);
tbjazic 0:8871082486ac 31 trigger = 0;
tbjazic 3:9a7899cf5e3a 32 wait_us(23660); // just enough time to measure 400 cm
tbjazic 3:9a7899cf5e3a 33 timer.stop(); // just in case echo fall did not occur
tbjazic 0:8871082486ac 34 distance = timer.read() * 1e6 / 58;
tbjazic 3:9a7899cf5e3a 35 if (distance < minDistance)
tbjazic 3:9a7899cf5e3a 36 distance = minDistance;
tbjazic 3:9a7899cf5e3a 37 if (distance > maxDistance)
tbjazic 3:9a7899cf5e3a 38 distance = maxDistance;
tbjazic 3:9a7899cf5e3a 39 timer.reset();
tbjazic 0:8871082486ac 40 }
tbjazic 0:8871082486ac 41
tbjazic 0:8871082486ac 42 float HCSR04::getDistance_cm() {
tbjazic 0:8871082486ac 43 startMeasurement();
tbjazic 0:8871082486ac 44 return distance;
tbjazic 0:8871082486ac 45 }