例程1、控制LED(4个LED灯)
1)、LED亮灭
import pyb
led=pyb.LED(2)
led.on()
pyb.delay(1000)
led.off()
2)、 LED翻转
import pyb
led = pyb.LED(4)
while True:
led.toggle()
pyb.delay(700)
3)、呼吸灯
import pyb
led = pyb.LED(4)
intensity = 0
while True:
intensity = (intensity + 1) % 255
led.intensity(intensity)
pyb.delay(10)
4)、流水灯
leds = [pyb.LED(i) for i in range(1,5)]
sw=pyb.Switch()
def test():
pyb.LED(1).on()
pyb.LED(2).on()
pyb.LED(3).on()
pyb.LED(4).on()
pyb.delay(2000)
sw.callback(test)
for l in leds:
l.off()
n = 0
try:
while True:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
finally:
for l in leds:
l.off()
5)、按键控制LED灯翻转
import pyb
sw = pyb.Switch()
def f():
pyb.LED(4).toggle()
sw.callback(f)
6)、定时器控制LED翻转
from pyb import Timer
tim4 = pyb.Timer(4)
tim7 = pyb.Timer(7)
tim4.init(freq=10)
tim7.init(freq=20)
led1 = pyb.LED(2)
led2 = pyb.LED(4)
tim4.callback(lambda t:led1.toggle())
tim7.callback(lambda t:led2.toggle())
7)、RTC控制LED翻转
import pyb
rtc = pyb.RTC()
rtc.datetime((2014,5,1,4,13,0,0,0))
print(rtc.datetime())
led = pyb.LED(3)
rtc.wakeup(500,lambda t:led.toggle())
例程2、获取I/O口的状态
from pyb import Pin
p_out = Pin('X1', Pin.OUT_PP) #设置引脚X1为推挽输出模式
p_out.high()
p_out.low()
p_in = Pin('X2', Pin.IN, Pin.PULL_UP)# 设置引脚X2为输入模式(具体哪种输入我也不是很清楚)
p_in.value() # get value, 0 or 1