-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
85 lines (75 loc) · 1.81 KB
/
main.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from machine import Pin, PWM, ADC
import utime
# 定义音符和频率
notes = {
'c': 261,
'd': 294,
'e': 329,
'f': 349,
'g': 392,
'a': 440,
'b': 494,
'C': 523,
'D': 587,
'E': 659,
'F': 698,
'G': 784,
'A': 880,
'B': 988
}
# 歌曲序列,每个元素是一个元组,包含音符、播放时间和停顿时间
song = [
# 祝你生日快乐
('g', 0.5, 0.05),
('g', 0.5, 0.1),
('a', 0.5, 0.1),
('g', 0.5, 0.1),
('C', 0.5, 0.1),
('b', 1, 0.1),
# 祝你生日快乐
('g', 0.5, 0.05),
('g', 0.5, 0.1),
('a', 0.5, 0.1),
('g', 0.5, 0.1),
('D', 0.5, 0.1),
('C', 1, 0.1),
# 祝你生日快乐
('g', 0.5, 0.05),
('g', 0.5, 0.1),
('G', 0.5, 0.1),
('E', 0.5, 0.1),
('C', 0.5, 0.1),
('b', 0.5, 0.1),
('a', 0.5, 0.1),
('a', 1, 0.1),
# 祝你生日快乐
('F', 0.5, 0.05),
('F', 0.5, 0.1),
('E', 0.5, 0.1),
('C', 0.5, 0.1),
('D', 0.5, 0.1),
('C', 1.5, 0.1)
]
# 无源蜂鸣器引脚
buzzer = PWM(Pin(16))
# 光敏电阻引脚
ldr = ADC(Pin(26))
# 通过PWM播放音符
def play_note(note, play_time, pause_time):
buzzer.freq(notes[note])
buzzer.duty_u16(2000) # 响度
utime.sleep(play_time)
buzzer.duty_u16(0)
utime.sleep(pause_time)
# 检查环境亮度并播放音乐
def check_light_and_play():
while True:
light_value = ldr.read_u16()
print(light_value)
utime.sleep(2)
if light_value > 4000: # 环境亮度阈值可以根据实际情况调整
for note, play_time, pause_time in song:
play_note(note, play_time, pause_time)
# 主程序
if __name__ == '__main__':
check_light_and_play()