# 导入必要的库
from machine import Pin, PWM, ADC
import time
adc_pin = 32 #adc pin
pwm_pin = 18 #''' Define the PWM pin '''
# 初始化ADC对象,指定ADC引脚
adc = ADC(adc_pin) #''' Call the ADC Pin and pass the ADC pin '''
#开启衰减器,测量量程增大到 3.3
adc.atten(ADC.ATTN_11DB) #''' Configure the atenuation level of the ADC for reading 3.3V '''
# 初始化PWM对象,指定PWM引脚(例如:GPIO 18) ''' Now statrt with the Pulse width modulation '''
pwm = PWM(Pin(pwm_pin)) #''' Call the the Pwm module and the passs the PWM module '''
# 定义音符持续时间(秒) #''' Set the duration of each tone '''
note_duration = 0.1
while True:
# 循环演奏曲目
# 设置PWM信号频率
analog_value = adc.read() #''' Read the adc value and save it as analog_value '''
pwm.freq(analog_value+1) #''' Change and update the frequency add 1 since frequency cannot be less than 1'''
# 播放音符
print(f"ADC_Value :{analog_value}" )
pwm.duty(512) # 设置占空比(范围:0-1023)
# 等待音符持续时间
time.sleep(note_duration)
# 停止音符
pwm.duty(0)
# 等待一段时间作为间隔
time.sleep(.1)