Micropython学习(三)常用库函数操作

 引脚图

 例程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

 

  • 12
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值