commit 52c6c2b2e8cfe2fccf6c1c2034454550de654513 Author: Kai Vogelgesang Date: Tue Jul 1 16:51:58 2025 +0200 Init diff --git a/ultrasound/.gitignore b/ultrasound/.gitignore new file mode 100644 index 0000000..7c0bf87 --- /dev/null +++ b/ultrasound/.gitignore @@ -0,0 +1,2 @@ +.venv +typings diff --git a/ultrasound/Makefile b/ultrasound/Makefile new file mode 100644 index 0000000..24842cd --- /dev/null +++ b/ultrasound/Makefile @@ -0,0 +1,7 @@ +.PHONY: deploy +deploy: + mpremote fs cp src/* : + +.PHONY: run +run: deploy + mpremote exec "import main; main.main()" diff --git a/ultrasound/README.md b/ultrasound/README.md new file mode 100644 index 0000000..08eba16 --- /dev/null +++ b/ultrasound/README.md @@ -0,0 +1,6 @@ +# Setup: +``` +$ python -m venv .venv +$ source .venv/bin/activate +$ pip install -U micropython-rp2-pico_w-stubs --no-user --target typings +``` diff --git a/ultrasound/pyproject.toml b/ultrasound/pyproject.toml new file mode 100644 index 0000000..65df247 --- /dev/null +++ b/ultrasound/pyproject.toml @@ -0,0 +1,7 @@ +[tool.basedpyright] +reportMissingModuleSource=false +reportUnusedCallResult=false +reportUnknownMemberType=false + +stubPath = "typings" +typeshedPath = "typings" \ No newline at end of file diff --git a/ultrasound/src/main.py b/ultrasound/src/main.py new file mode 100644 index 0000000..595895d --- /dev/null +++ b/ultrasound/src/main.py @@ -0,0 +1,79 @@ +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()