80 lines
1.7 KiB
Python
80 lines
1.7 KiB
Python
from machine import Pin
|
|
import machine
|
|
import time
|
|
import asyncio
|
|
|
|
class StatusLED:
|
|
led: Pin
|
|
_status: int
|
|
_period: float
|
|
_duty_cycle: float
|
|
|
|
def __init__(self):
|
|
self.led = Pin("LED", Pin.OUT)
|
|
self._status = 1
|
|
self._period = 1
|
|
self._duty_cycle = 0.5
|
|
|
|
def status(self, status: int):
|
|
self._status = status
|
|
|
|
|
|
async def task(self):
|
|
while True:
|
|
t_1 = self._duty_cycle * self._period
|
|
t_2 = (1 - self._duty_cycle) * self._period
|
|
|
|
t_blink = t_1 / self._status / 2
|
|
for _ in range(self._status):
|
|
self.led.value(1)
|
|
await asyncio.sleep(t_blink)
|
|
self.led.value(0)
|
|
await asyncio.sleep(t_blink)
|
|
|
|
await asyncio.sleep(t_2)
|
|
|
|
STATUS_LED = StatusLED()
|
|
|
|
|
|
class UltraSonicSensor:
|
|
"""
|
|
See https://randomnerdtutorials.com/micropython-hc-sr04-ultrasonic-esp32-esp8266/
|
|
"""
|
|
|
|
tx: Pin
|
|
rx: Pin
|
|
|
|
def __init__(self, tx: int, rx: int):
|
|
self.tx = Pin(tx, Pin.OUT)
|
|
self.rx = Pin(rx, Pin.IN)
|
|
|
|
def query_mm(self):
|
|
self.tx.value(0)
|
|
time.sleep_us(5)
|
|
self.tx.value(1)
|
|
time.sleep_us(10)
|
|
self.tx.value(0)
|
|
|
|
pulse_time = machine.time_pulse_us(self.rx, 1, 500*2*30)
|
|
if pulse_time < 0:
|
|
return None
|
|
|
|
return pulse_time * 100 // 582
|
|
|
|
|
|
|
|
async def _main():
|
|
asyncio.create_task(STATUS_LED.task())
|
|
sensor = UltraSonicSensor(22, 21)
|
|
while True:
|
|
d = sensor.query_mm()
|
|
print(f"d: {d} mm")
|
|
await asyncio.sleep(0.5)
|
|
|
|
def main():
|
|
asyncio.run(_main())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|