下载micropython固件后,先进行一些基本功能测试。
闪灯
from machine import Pin
from time import sleep_ms
LED=Pin(15,Pin.OUT)
while 1:
LED(not LED())
sleep_ms(200)
呼吸灯(使用定时器周期设置PWM占空比)
from machine import Pin, PWM, Timer
LED = PWM(Pin(15), freq=1000)
n = 0
def breathing(t):
global n
LED.duty(abs(1023- n*32))
n = (n + 1) % 64
T0 = Timer(0)
T0.init(period=50, mode=Timer.PERIODIC, callback=breathing)
读取按键
from machine import Pin
from time import sleep_ms
sw=Pin(9, Pin.IN)
while 1:
sw()
sleep_ms(200)
使用Signal方式读取按键(sw信号是通过电阻上拉到VCC的,按下时是低电平,释放时是高电平。直接读取时按下按钮是低,未按下时是高,逻辑上上反的,使用signal,就可以变为正逻辑)
from machine import Pin, Signal
from time import sleep_ms
sw=Signal(Pin(9, Pin.IN), invert=True)
while 1:
sw()
sleep_ms(200)
按键中断,按下按钮翻转LED
from machine import Pin, Signal
sw=Pin(9, Pin.IN)
LED=Signal(Pin(15,Pin.OUT))
sw.irq(trigger=Pin.IRQ_FALLING, handler=lambda t: LED(not LED()))
ADC(读取电池电压,如果未接入电池,输出为4.2V左右)
from machine import ADC, Pin
aVBAT = ADC(Pin(0), atten=ADC.ATTN_11DB)
def VBAT():
return aVBAT.read_uv()*2/1000000
查看内部文件系统大小
import os
os.statvfs('/')
例如返回值是:(4096, 4096, 512, 509, 509, 0, 0, 0, 0, 255)
磁盘大小:4096*512=2097152
2097152/1024/1024=2.0M
剩余空间大小:4096*509=2084864
2084864/1024**2=1.988281M
搜索网络
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.scan()
正常情况下,返回带有可见路由器信息的元组列表。
连接网络
import network
w=network.WLAN(network.STA_IF)
w.active(1)
w.connect('ssid','password')
w.isconnected()
注意替换上面的 siid 和 password。
ntptime(假设已经联网)
>>> import ntptime
>>> ntptime.host
'pool.ntp.org'
>>> ntptime.utime.localtime()
(2000, 1, 1, 13, 30, 55, 5, 1)
>>> ntptime.settime()
>>> ntptime.utime.localtime()
(2024, 4, 26, 2, 55, 55, 4, 117)