大家好,这一次讲一下定时器的使用。
环境依然是MicroPython,Wokwi仿真,树莓派Pico。不会搭建的同学请看笔记(1),谢谢!
一、目的
实现使用定时器让LED间隔500ms闪烁。
二、代码
这里初始化了一个timer,它周期性的每秒调用2次函数Flash_LED,此处闪灯使用的是toggle函数(toggle就是实现LED灯的状态转换)。
注意:和其他单片机一样,中断函数中最好不要执行太多语句,否则会出现难以预料的错误。
main.py: 代码中callback回调函数Flash_LED, 实现LED闪烁的效果。
# 这个例子是实现定时器
from machine import Pin,Timer
LED = Pin(7, Pin.OUT) # 端口7
tim = Timer()
def Flash_LED(tim):
global LED
LED.toggle()
# 频率设为4,即每秒闪烁4次;PERIODIC代表周期性执行
#tim.init(freq = 4, mode = Timer.PERIODIC,callback = Flash_LED)
# 频率设为2,即每秒闪烁2次;ONE_SHOT代表执行一次
# tim.init(freq = 2, mode = Timer.ONE_SHOT,callback = Flash_LED)
# 每100ms周期性的闪烁
#tim.init(period = 100, mode = Timer.PERIODIC,callback = Flash_LED)
diagram.json:
{
"version": 1,
"author": "Anonymous maker",
"editor": "wokwi",
"parts": [
{
"type": "wokwi-pi-pico",
"id": "pico",
"top": -52.98,
"left": -5.98,
"attrs": { "env": "micropython-20220117-v1.18" }
},
{
"type": "wokwi-led",
"id": "led1",
"top": -3.71,
"left": 117.56,
"attrs": { "color": "white", "flip": "", "lightColor": "blue" }
},
{
"type": "wokwi-resistor",
"id": "r1",
"top": 96.97,
"left": 91.4,
"rotate": 180,
"attrs": { "value": "470" }
}
],
"connections": [
[ "led1:C", "r1:1", "green", [ "v35.22", "h26.2" ] ],
[ "r1:2", "pico:GND.6", "green", [ "v0" ] ],
[ "led1:A", "pico:GP7", "green", [ "v0" ] ]
]
}
到这里大家对定时器应该有一个基础的了解了吧。加油,小伙伴们!