from machine import Pin
import time
import dht
Echo_PIN = 13
TRIG_PIN = 11
dht22_pin = 17
Echo = Pin(Echo_PIN, Pin.IN)
Trig = Pin(TRIG_PIN, Pin.OUT)
sensor = dht.DHT22(dht22_pin)
def get_distance(temp):
Trig.value(1)
time.sleep_us(10)
Trig.value(0)
while Echo.value() == 0:
start_time = time.ticks_us()
while Echo.value() == 1:
end_time = time.ticks_us()
T = time.ticks_diff(end_time, start_time)
distance = ((T / 2) * (331 + (0.6 * temp))) / 10000
distance_1 = round(distance, 2)
return distance_1
while True:
try:
sensor.measure()
temperature = sensor.temperature()
hum = sensor.humidity()
distance = get_distance(temperature)
print("Distance: {:.2f} cm\n".format(distance))
print("Temperature: {:.2f} C\n".format(temperature))
print("Humidity: {:.2f} %\n".format(hum))
except OSError as e:
print('Failed to read sensor.')
time.sleep(5)