from machine import Pin, time_pulse_us
import time
echo = Pin(23, Pin.IN)
trigger = Pin(13, Pin.OUT)
botao = Pin(25, Pin.IN, Pin.PULL_DOWN)
def mede(trigger, echo):
trigger.value(0)
time.sleep_us(2)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
t = time_pulse_us(echo, 1, 30000)
if t < 0:
return 0
distancia = (t / 2) / 29.1
return distancia
atual = 0
while True:
novo = botao.value()
if novo == 1 and atual == 0:
leituras = []
contador = 0
while contador < 5:
dist = mede(trigger, echo)
if dist > 0:
leituras = leituras + [dist]
contador += 1
time.sleep(0.1)
if leituras:
media = sum(leituras) / len(leituras)
print(f"Média das distâncias: {media:.2f} cm")
else:
print("Todas as medições falharam")
atual = novo
time.sleep(0.05)Loading
esp32-devkit-c-v4
esp32-devkit-c-v4