Fork Star Issue Watch
sudo apt install python3-pip python3-rpi.gpio sudo pip3 install hcsr04sensor
The module does the following;
Returns an error corrected distance by using the median reading of a sorted sample. NOTE - The default sample size is 11 readings.
This module supports BCM and BOARD pin values but uses BCM by default. See the Raspberry Pi pin layout documentation for your model.
Adjusts the reading based on temperature by adjusting the speed of sound.
Allows measuring distance or depth in metric and imperial units.
Allows measuring volume in (litres/gallons) of various shaped containers (cuboid, cylinders, elliptical cylinders).
Raises an exception if a faulty cable or sensor prevents an echo pulse from being received.
Free to use under the MIT License
GPIO pins are rated for 3.3V so you must insert a voltage divider as the power pin on the PI is 5V. In the above diagram a 470 Ohm resistor is soldered on the echo wire. A 1000 Ohm resistor is soldered between the echo and ground wires. This reduces voltage to GPIO pin 27 to 3.4V which is within a tolerable level. Failure to do this can damage your board.
pi@raspberry:~ $ hcsr04.py -h usage: hcsr04.py [-h] -t TRIG -e ECHO [-sp SPEED] [-ss SAMPLES] Script tests the HCSR04 sensor under different configurations optional arguments: -h, --help show this help message and exit -t TRIG, --trig TRIG Trig Pin (Required - must be an integer) -e ECHO, --echo ECHO Echo Pin (Required - must be an integer) -sp SPEED, --speed SPEED Time between individual reading samples (Optional - must be a float, default is 0.1 seconds) -ss SAMPLES, --samples SAMPLES Reading Sample Size (Optional - must be an integer, default is 11)Sample Output
pi@raspberry:~ $ hcsr04.py -t 17 -e 27 trig pin = gpio 17 echo pin = gpio 27 speed = 0.1 samples = 11 The imperial distance is 12.3 inches. The metric distance is 31.2 centimetres.
Various recipes for measuring distance or liquid depth.
HC-SR04 Specification Manual
JSN-SR04T Specification Manual