开始学习
< 返回

树莓派 Pico 快速上手

树莓派 Pico 快速上手

使用 Micro USB 线连接 Raspberry Pi Pico 到你的电脑,打开串口终端。Ubuntu 用户可以使用 minicom 命令,如下:

sudo minicom -D /dev/ttyACM0

此时,我们会进入 MicroPython 的 REPL 命令交互模式,可以直接输入 MicroPython 命令进行测试。

REPL 是 Read Eval Print Loop 的缩写,它是 MicroPython 解释器的交互式模式。也就是说,通过 REPL,我们可以通过串行接口(UART 或 USB)直接输入 MicroPython 语句并进行解释执行。

示例 1:Hello, Pico!

在串口终端输入 print("Hello, Pico!"),Pico 会打印 Hello, Pico!

>>> print("Hello, Pico!")
Hello, Pico!

示例 2:点亮 LED

在串口终端输入下面 MicroPython 代码:

from machine import Pin
led = Pin(25, Pin.OUT)
led.value(1)

可以看到,Raspberry Pi Pico 板载的 LED 等被点亮!

熄灭 LED 代码:

led.value(0)

示例 3:LED 闪烁

from machine import Pin
import utime
led = Pin(25, Pin.OUT)
loop = 10

def blink(loop=10):
    while loop:
        led(1)
        utime.sleep(0.5)
        led(0)
        utime.sleep(0.5)
        loop -= 1

提示:由于 REPL 提供了 Auto-Indent(自动缩进)功能,如果一次性粘贴上述代码到串口终端,会造成缩进不对齐的问题,因此需要逐行输入。

现在,你可以调用 blink() 函数让 LED 灯闪烁起来!

blink()

默认闪烁 10 次,可以传入参数调整闪烁次数,例如闪烁 60 次(1 分钟)。

blink(60)

示例 4:定时器

下面使用定时器中断方式来闪烁 LED,代码如下:

from machine import Pin, Timer
led = Pin(25, Pin.OUT)
timer = Timer()

def led_toggle(timer):
    global led
    led.toggle()

timer.init(freq=2, mode=Timer.PERIODIC, callback=led_toggle)

现在,你应该可以看到 LED 正在闪烁。

Was this article helpful?
0 out of 5 stars
5 Stars 0%
4 Stars 0%
3 Stars 0%
2 Stars 0%
1 Stars 0%
Please Share Your Feedback
How Can We Improve This Article?
文章目录