Class library for a HC-SR04 Distance Sensor based on PwmOut (Trig) and InterruptIn (Echo).
Dependents: ultra TDPS-COM1 HCSR04
HCSR04.h
- Committer:
- grantphillips
- Date:
- 2016-02-08
- Revision:
- 0:5541303b14e7
- Child:
- 1:8286d0de19ce
File content as of revision 0:5541303b14e7:
/* HCSR04 Library v1.0 * Copyright (c) 2016 Grant Phillips * grant.phillips@nmmu.ac.za * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef HCSR04_H #define HCSR04_H #include "mbed.h" /** HC-SR04 Distance Sensor class based on PwmOut (Trig) and InterruptIn (Echo). * * Example: * @code * #include "mbed.h" * #include "HCSR04.h" * * HCSR04 distance(PB_8, PA_1); * * int main() { * while(1){ * SWO.printf("Distance = %d (us) %f (cm)\n", distance.read_us(), distance.read_cm()); * } * } * @endcode */ class HCSR04 { public: /** Create a HCSR04 object connected to the specified pins. Once created, the PWM signal * on the Trig pin will start immediately and measurements will start in the background. * @param TrigPin PwmOut compatible pin used to connect to HC-SR04's Trig pin * @param EchoPin InterruptIn compatible pin used to connect to HC-SR04's Echo pin */ HCSR04(PinName TrigPin, PinName EchoPin); /** Return the current pulse duration as microseconds (us). * @param * None * @return * Duration as microseconds. */ unsigned int read_us(); /** Return the current pulse duration as centimeters (cm). * @param * None * @return * Duration as centimeters. */ float read_cm(); private: PwmOut trig; InterruptIn echo; Timer timer; long us; void HighTrigger(); void LowTrigger(); }; #endif