Last active
February 18, 2024 10:09
-
-
Save Dan-in-CA/681a1a705cc80330e0a7ed48662492c6 to your computer and use it in GitHub Desktop.
pigpio code for wateproof ultrasonic sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# By Dan-in-CA 11/2018 | |
# Updated 3/21/2019 | |
from __future__ import print_function, division | |
from time import sleep | |
import pigpio | |
pi = pigpio.pi() | |
# Define GPIO pins to use on Pi (BMC numbering) | |
pin_trigger = 23 | |
pin_echo = 24 | |
start = None | |
prev = 0 | |
max_dif = 10 | |
distance = None | |
verbose = False | |
# Speed of sound in cm/ms at temperature (changed from cm/s) | |
temperature = 24 | |
sound_speed = 33.1 + (0.0006*temperature) | |
# Set pin modes and output level | |
pi.set_mode(pin_trigger, pigpio.OUTPUT) | |
pi.write(pin_trigger, 0) | |
pi.set_mode(pin_echo, pigpio.INPUT) | |
def calc(gpio, level, tick): | |
""" | |
Callback function to handle distance calculation. | |
""" | |
global start, prev, distance | |
if level == 1: # Start of echo pulse | |
start = tick | |
if start and level == 0: # If start has a value and echo pulse ended | |
echo = pigpio.tickDiff(start, tick) # Length of echo pulse in microseconds | |
if verbose: | |
print("echo: ", echo) | |
dist = round(((echo / 1000) * sound_speed)/2, 1) | |
if not abs(prev - dist) > max_dif: #### May want to make this user setable | |
distance = dist | |
prev = dist | |
start = None | |
return | |
def measure(): | |
""" | |
Send a pulse and time the echo. | |
""" | |
pi.gpio_trigger(pin_trigger, 10, 1) # Send a 10 microsecond pulse on the trigger pin | |
cb = pi.callback(pin_echo, pigpio.EITHER_EDGE, calc) # Catch the echo pulse and pass timing to calc callback function | |
sleep(0.1) | |
cb.cancel() | |
if verbose and distance: | |
print("distance: ", distance) | |
return distance | |
if __name__ == '__main__': | |
verbose = True | |
while True: | |
measure() | |
sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment