Archived
1
0
This repository has been archived on 2025-04-27. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
pico-hcsr04/hcsr04_funcs.py
2022-12-30 23:03:38 -05:00

34 lines
790 B
Python

import time
'''
hcsr04_funcs: Helper functions to interact with the HC-SR04 sensor.
'''
def read_hc_sr04(trig, echo):
"""
reads the HC-SR04 sensor.
returns tuple(temperature, humidity) if no errors
returns None if there was an error
"""
try:
trig.value(0)
time.sleep(0.1)
trig.value(1)
time.sleep_us(2)
trig.value(0)
while echo.value()==0:
pulse_start = time.ticks_us()
while echo.value()==1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17165 / 1000000
distance = round(distance, 2)
return distance
except:
return None