-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactivated light.py
More file actions
59 lines (51 loc) · 1.72 KB
/
activated light.py
File metadata and controls
59 lines (51 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#EC800M
import audio
import _thread
import uos
import utime
from machine import Pin
# 初始化录音对象
record = audio.Record()
# 全局标志位,用于控制线程退出
thread_running = True
# 声控灯线程函数
def sound_control_thread():
global thread_running
print('声控灯线程启动')
while thread_running:
print('等待录音...')
try:
# 删除旧的录音文件
if uos.exists('record.wav'):
uos.remove('record.wav')
print('删除旧的录音文件')
else:
print('录音文件不存在,无需删除')
# 开始录音
record.start('record.wav', 3) # 录音 3 秒
print('录音中...')
utime.sleep(3) # 等待录音完成
# 检查录音文件是否有内容
file_info = uos.stat('record.wav')
if file_info[6] > 0: # 文件大小大于 0,表示录音成功
print("检测到声音,开灯")
led.write(1) # 打开 LED
utime.sleep(3) # 保持灯亮 3 秒
led.write(0) # 关闭 LED
print("LED 已关闭")
else:
print("未检测到声音")
except Exception as e:
print("发生错误: ",e)
if __name__ == '__main__':
# 初始化 LED 引脚
led = Pin(Pin.GPIO1, Pin.OUT, Pin.PULL_DISABLE, 0)
# 启动声控灯线程
_thread.start_new_thread(sound_control_thread, ())
try:
while True:
utime.sleep(1)
except KeyboardInterrupt:
print("程序终止,正在退出...")
thread_running = False # 通知线程退出
utime.sleep(1) # 等待线程退出