1、
from machine import Pin
import time
# 定义按键引脚控制对象
key1 = Pin(27,Pin.IN, Pin.PULL UP)
key2 = Pin(26,Pin.IN, Pin.PULL UP)
led1 = Pin(15,Pin.ouT, value=0)
led2 = Pin(2,Pin.ouT, value=0)
led3 = Pin(0,Pin.ouT, value=0)
# 定义key1按键中断处理函数
def key1 irq(key1):
time.sleep_ms(10)# 按键去抖
if key1.value()== 0:
led1.value(not led1.value())
#定义key2按键中断处理函数
def key2 irq(key2):
time.sleep_ms(10)# 按键去抖
if key2.value()== 0:
led2.value(not led2.value())
if __name__=="__main__":
key1.irq(key1 irq, Pin.IRQ FALLING)
key2.irq(key2_irq, Pin.IRQ FALLING)
while True:
led3.value( not led3.value())
time.sleep ms(500)
2、
from machine import Pin
from machine import PWM
import time
if __name__=="__main__":
beep_pwm=PWM(Pin(4),freq=2700,duty=512)
# beep_pwm.duty(512)
# time.sleep(1)
# beep pwm.deinit()
print("play music:")
# 音符对应的频率
music_freq_list=[
0,#None
1046,#1
1175,#2
1318,#3
1379,#4
1568,#5
1760,#6
1976,#7
395,#低音5
]
# 两只老虎音乐简谱
music_note_list=[
1,2,3,1,
1 2 3 1,
3,4,5,
3,4,5,
5,6,5,4 3 1,
5,6,5,4 3 1,
1,8,1,
1 8,1,
]
# 曲谱时值(每个音符是几个节拍)
music_beat_list =[
4,4,4,4,
4,4,4,4,
4,4,8,
4,4,8,
3,1,3,1,4,4,
3,1,3,1,4,4,
4,4,8,
4,4,8,
]
# 遍历简谱,让beep播放对应频率的声音
for i in range(len(music_note_list)):
music_note=music_note_list[i]# 取出第i个音符
music_freq=music_freq_list[music_note]# 音符对应的频率
music beat=music_beat_list[i]* 125#每个节拍时间125毫秒
# 控制蜂鸣器发音
beep_pwm.freq(music_freg)
time.sleep ms(music_beat)
#停止
print("stop")
beep_pwm.deinit()
3、
from machine import Pin
from machine import ADc
from machine import Timer
#定义ADC对象,使用34号引脚作为输入通道(不能随时使用其他引脚)
adc = ADC(Pin(34))
# 配置11DB衰减器,增大测量范围
adc.atten(ADC.ATTN_11DB)
def timer0_irg(timer0):
# 读取ADC返回的数字值,默认分辨率12,数字范围0~4095
adc_value = adc.read()
print("ADC转换的数字值:%d"% adc_value)
# 根据数字值,计算模拟值
adc_vol=3.3*adc_value /4095
print("ADC检测到的电压值:%.2f"% adc_vol)
if __name__== "__main__":
timer0 =Timer(0)
timer0.init(period=1000,mode=Timer.PERIODIC, callback=timer0_irq)
while True :
pass
4、
from machine import Pin, ADc, Timen
adc = ADC(Pin(34))# 连接光敏模块A0引脚
adc.atten(ADC.ATTN_11DB)
def read_lux(timer0):
# 读取ADC的值(光敏电阻转换数字值)
adc_value = adc.read()
# 估算光照强度
lux=100-(100*adc_value / 4095)
print("lux:%d"% lux)
if __name__=='__main__':
timer0 = Timer(0)
timer0.init(period=1000,mode=Timer.PERIODIC, callback=read_lux)
while True :
pass
5、
from machine import Pin, ADc, Timer
#from time import sleep
adc = ADC(Pin(34))# 连接A0
adc.atten(ADC.ATTN _11DB)
rain= Pin(26,Pin.IN, Pin.PULL_UP)# 连接DO
def read_raindrop(timer0):# 读取A0输出值:0~4095
rain_value = adc.read()
print("A0=%d" % rain_value)
# 读取数字输出:0/1
print("Do=%d"% rain.value())# A0输出值达到阈值时,输出0
if __name__=="__main__":
timer0 =Timer(0)
timer0.init(period=1000,mode=Timer.PERIODIC, callback=read_raindrop)
while True :
pass
6、
from machine import Pin
def shock_irq(pin):
print("检测到振动!")
if __name__=="__main__":
shock_pin =Pin(15,Pin.IN, Pin.PULL_DOWN)
shock_pin.irq(trigger=Pin.IRQ_RISING, handler=shock_irq)
while True:
pass