RPi::HCSR04 - Interface to the HC-SR04 ultrasonic distance measurement sensor on the Raspberry Pi
use RPi::HCSR04; my $trig_pin = 23; my $echo_pin = 24; my $sensor = RPi::HCSR04->new($trig_pin, $echo_pin); my $inches = $sensor->inch; my $cm = $sensor->cm; my $raw = $sensor->raw; ...
Easy to use interface to retrieve distance measurements from the HC-SR04 ultrasonic distance measurement sensor.
Requires wiringPi to be installed.
This software does no timing whatsoever; it operates as fast as your device will allow it.
This often causes odd results. It's recommended that if you put your checks within a loop, to sleep for at least two milliseconds (0.02). You can use select(undef, undef, undef, 0.02);, or usleep() from Time::HiRes.
0.02
select(undef, undef, undef, 0.02);
usleep()
The HC-SR04 sensor requires 5V input, and that is returned back to a Pi GPIO pin from the ECHO output on the sensor. The GPIO on the Pi can only handle a maximum of 3.3V in, so either a voltage regulator or a voltage divider must be used to ensure you don't damage the Pi.
ECHO
Here's a diagram showing how to create a voltage divider with a 1k and a 2k Ohm resistor to lower the ECHO voltage output down to a safe ~3.29V. In this case, TRIG is connected to GPIO 23, and ECHO is connected to GPIO 24.
TRIG
Instantiates and returns a new RPi::HCSR04 object.
Parameters:
$trig
Mandatory: Integer, the GPIO pin number of the Raspberry Pi that the TRIG pin is connected to.
$echo
Mandatory: Integer, the GPIO pin number of the Raspberry Pi that the ECHO pin is connected to.
Returns a floating point number containing the distance in inches. Takes no parameters.
Returns a floating point number containing the distance in centemetres. Takes no parameters.
Returns an integer representing the return from the sensor in raw original form. Takes no parameters.
wiringPi must be installed.
You must regulate the voltage from the ECHO pin down to a safe 3.3V from the 5V input. See "VOLTAGE DIVIDER" for details.
Steve Bertrand, <steveb at cpan.org>
<steveb at cpan.org>
Copyright 2017 Steve Bertrand.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.
To install RPi::HCSR04, copy and paste the appropriate command in to your terminal.
cpanm
cpanm RPi::HCSR04
CPAN shell
perl -MCPAN -e shell install RPi::HCSR04
For more information on module installation, please visit the detailed CPAN module installation guide.