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,#None1046,#11175,#21318,#31379,#41568,#51760,#61976,#7395,#低音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~4095adc_value = adc.read()print("ADC转换的数字值:%d"% adc_value)# 根据数字值,计算模拟值adc_vol=3.3*adc_value /4095print("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 sleepadc = ADC(Pin(34))# 连接A0
adc.atten(ADC.ATTN _11DB)rain= Pin(26,Pin.IN, Pin.PULL_UP)# 连接DOdef read_raindrop(timer0):# 读取A0输出值:0~4095rain_value = adc.read()print("A0=%d" % rain_value)# 读取数字输出:0/1print("Do=%d"% rain.value())# A0输出值达到阈值时,输出0if __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