更新MPY一些库优化,及增加微波雷达,语音播放库

This commit is contained in:
dahanzimin
2024-11-13 15:29:50 +08:00
parent b6cfd8a5b0
commit bbaa6587c5
7 changed files with 343 additions and 94 deletions

View File

@@ -1,23 +1,39 @@
from machine import Pin
import time
"""
CS100/HC-SR04
Micropython library for the CS100/HC-SR04(Ultrasonic ranging)
=======================================================
@dahanzimin From the Mixly Team
"""
from time import sleep_us
from machine import Pin, time_pulse_us
# Sonar
class Sonar:
def __init__(self, trig, echo):
self.trig=Pin(trig, Pin.OUT)
self.echo=Pin(echo, Pin.IN)
__species = {}
__first_init = True
def checkdist(self):
#trig, echo = Pin(trig, Pin.OUT), Pin(echo, Pin.IN)
self.trig.value(0)
self.echo.value(0)
self.trig.value(1)
time.sleep_us(10)
self.trig.value(0)
while(self.echo.value()==0):
pass
t1 = time.ticks_us()
while(self.echo.value()==1):
pass
t2 = time.ticks_us()
return round(time.ticks_diff(t2, t1) / 10000 * 340 / 2, 2)
def __new__(cls, trig, echo, *args, **kwargs):
if (trig, echo) not in cls.__species.keys():
cls.__first_init = True
cls.__species[(trig, echo) ] = object.__new__(cls)
return cls.__species[(trig, echo)]
def __init__(self, trig, echo, max_rang=400):
if self.__first_init:
self.__first_init = False
self.trig = Pin(trig, Pin.OUT, value=0)
self.echo = Pin(echo, Pin.IN)
self.timeout_us = int(max_rang * 2 * 29.1)
def checkdist(self):
self.trig.value(0)
sleep_us(5)
self.trig.value(1)
sleep_us(10)
self.trig.value(0)
try:
pulse_time = time_pulse_us(self.echo, 1, self.timeout_us)
pulse_time = pulse_time if pulse_time >= 0 else self.timeout_us
return round(pulse_time / 2 / 29.1, 2) # 1cm each 29.1us
except:
return None