Class library for a HC-SR04 Distance Sensor based on PwmOut (Trig) and InterruptIn (Echo).

Dependents:   ultra

Embed: (wiki syntax)

« Back to documentation index

HCSR04 Class Reference

HCSR04 Class Reference

Class library for a HC-SR04 Distance Sensor based on PwmOut (Trig) and InterruptIn (Echo). More...

#include <HCSR04.h>

Public Member Functions

 HCSR04 (PinName TrigPin, PinName EchoPin)
 Create a HCSR04 object connected to the specified pins.
unsigned int read_us ()
 Return the current pulse duration as microseconds (us).
float read_cm ()
 Return the current pulse duration as centimeters (cm).

Detailed Description

Class library for a HC-SR04 Distance Sensor based on PwmOut (Trig) and InterruptIn (Echo).

Example:

 #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()); 
     }
 }

Definition at line 47 of file HCSR04.h.


Constructor & Destructor Documentation

HCSR04 ( PinName  TrigPin,
PinName  EchoPin 
)

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.

Parameters:
TrigPinPwmOut compatible pin used to connect to HC-SR04's Trig pin
EchoPinInterruptIn compatible pin used to connect to HC-SR04's Echo pin

Definition at line 5 of file HCSR04.cpp.


Member Function Documentation

float read_cm (  )

Return the current pulse duration as centimeters (cm).

Parameters:
None
Returns:
Duration as centimeters.

Definition at line 16 of file HCSR04.cpp.

unsigned int read_us (  )

Return the current pulse duration as microseconds (us).

Parameters:
None
Returns:
Duration as microseconds.

Definition at line 12 of file HCSR04.cpp.