▌01 PI PICO
颜色名 | 十六进制颜色值 | 颜色 |
---|---|---|
Coral | #FF7F50 | rgb(255, 127, 80) |
1.安装与上载程序
在 RASPBERRY PI PICO 树莓派PICO开发板双核高性能低功耗RP2040芯片 给出了PI PICO的购买,制作以及进行MicroPython的初始化的过程。特别是,对于Window7下,MicroPython初始化之后,对于USB对应的CDC驱动需要手动进行安装。安装之后就会在Windows中出现 “Pi Pico Serial Port(COM6)”对应的串口。 其中COM6的具体端口号根据电脑原本具有的串口的配置有关系。
在正确配置之后,便可以通过串口的交互,利用 REPL 进行交互执行测试程序了。
本文给出了使用Python自动通过串口将MicroPython上载到PI Pico进行允许的过程。详细的程序在 附录 1.自动上载MicroPython的Python给出。
2.MicroPython手册
对应的PI PICO 的MicroPython应用程序开发可以参见: PI Pico MicroPython开发数据手册
3.REPL
REPL(read_eval_print_loop)是MicroPython的用户交互模式。通过REPL MicroPython程序可以动态接收通过串行接口(UART,USB)用户输入的MicroPython的语句并进行解释执行。
为了便于用户的手工输入,REPL提供了Auto-Indent(自动缩进)功能,也就是根据输入的语句是否有冒号(:)结尾来在下一行输入时,自动增加自动缩进(Auto-Indent)的功能,这样会节省用户输入行首的空格。在Python语言中,它是根据每一行的行首空格的多少(对应的缩进级别Level)来定义编程语法功能区域,比如for, if, while,def 等等。
但是由于存在REPL的auto-indent功能,这也给自动程序加载造成了一定的麻烦。这一点在RASPBERRY PI PICO 树莓派PICO开发板双核高性能低功耗RP2040芯片实验中会发现,如果将Python文本程序通过串口发送到PI Pico,会因为有缩进造成实际接收到的程序与原来程序文本不同。
比如,原本如下的程序:
def foo():
print('This is a test to show paste mode')
print('Here is a second line')
foo()
在Auto-Indent的功能下,MicroPython接收到的信息如下:
>>> def foo():
... print('This is a test to show paste mode')
... print('Here is a second line')
... foo()
...
File "<stdin>", line 3
IndentationError: unexpected indent
根据MicroPython官方对于REPL的定义: MicroPython:REPL for upload file 可以利用REPL中通过CTRL-A,CTRL-B,CTRL-C,CTRL-D ( 具体CTRL-字符的编码 ) 等控制命令来切换AutoIndent的功能。
在MicroPython的REPL中使用CTRL-E(0x05)来使REPL切换到PASTE功能,当输入完所有的程序之后,通过CTRL-D(0x04)将REPL退出PASTE模式,并开始编译直接刚刚输入的命令。
Useful control commands:
CTRL-C -- interrupt a running program
CTRL-D -- on a blank line, do a soft reset of the board
CTRL-E -- on a blank line, enter paste mode
▌02 基本实验
1.基本测试程序
在附件2中给出了一个基本测试程序,包括以下三个功能:
- 使用定时器的Callback功能,驱动板载LED(pin25)闪烁;
- 输出 0~9的平方
- 输出’hello’
执行udpppp之后,PI PICO串口反馈信息:
Open sport port COM6 Ok.
MPY: soft reboot
MicroPython v1.14 on 2021-02-24; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
>>>
>>> from machine import Pin, Timer
>>> led = Pin(25, Pin.OUT)
>>> tim = Timer()
>>>
>>> def tick(timer):
... global led
... led.toggle()
...
...
...
>>> tim.init(freq=5, mode=Timer.PERIODIC, callback=tick)
>>>
>>> for i in range(10):
... print(i**2)
...
...
...
0
1
4
9
16
25
36
49
64
81
>>> print('hello')
hello
>>>
>>>
>>>
▲ PI PICO执行程序现象
2.测试UART
▲ 串口1发送0x55,测量PIN4波形
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# TESTUART.PY -- by Dr. ZhuoQing 2021-02-24
#
# Note:
#============================================================
from head import *
from machine import UART,Pin
from time import sleep_us
uart = UART(1, baudrate=115200, tx=Pin(4), rx=Pin(5), bits=8, parity=None, stop=1)
led = Pin(25, Pin.OUT)
count = 0
for _ in range(100000):
uart.write(b'\x55')
sleep_us(1000)
#------------------------------------------------------------
# END OF FILE : TESTUART.PY
#============================================================
※ 附录
1.自动上载MicroPython至PI Pico程序
```python
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# UPPPP.PY -- by Dr. ZhuoQing 2021-02-24
# Upload PI Pico Program.
# Usage:
# upppp filename COM1 & 100
# upppp * # Paste file into Thonny & execute
#
# Note:
#============================================================
from head import *
import serial
from _ast import Or
from serial.serialutil import SerialException
#------------------------------------------------------------
THONNY_WINDOW = 'Thonny'
def ThonnyExec():
tspcopyclipboard()
blanklineflag = 1
clipstr = clipboard.paste().split('\n')
pastr = []
lastpasteline = ''
for s in clipstr:
if len(s) == 0: continue
ss = s.lstrip(' ')
if len(ss) > 0:
if ss[0] == '#': continue
if ss.find('from head') >= 0: continue
if len(ss) < 2:
if blanklineflag != 0:
continue
blanklineflag = 1
else:
blanklineflag = 0
else:
if blanklineflag != 0:
continue
blanklineflag = 1
if len(lastpasteline) > 0:
pastr.append(lastpasteline)
lastpasteline = s
if len(lastpasteline) > 0:
pastr.append(lastpasteline)
if len(lastpasteline) > 2:
pastr.append("\r")
copystr = '\n'.join(pastr)
tspcopystring(copystr)
tspsendwindowkey(THONNY_WINDOW, "e", alt=1)
tspsendwindowkey(THONNY_WINDOW, "av", control=1)
tspsendwindowkey(THONNY_WINDOW, '%c'%(0x74), vk=1)
tspfocuswindow("TEASOFT:1")
printf("\a")
#------------------------------------------------------------
if len(sys.argv) > 1:
if sys.argv[1] in '. ; *':
ThonnyExec()
printf("\a")
exit()
#------------------------------------------------------------
title = tspgetwindowtitle()
for t in title:
if t.find('Thonny') == 0:
ThonnyExec()
printf("\a")
exit()
#------------------------------------------------------------
PORTNAME = 'COM6'
WAITTIMEMS = 500
WAIT_LOOP = 0
#------------------------------------------------------------
doppath = tspgetdoppath()
filename = tspeditfileget()
#filename = os.path.join(doppath, 'testpwm.py')
printf(filename)
#------------------------------------------------------------
if len(sys.argv) > 1:
for v in sys.argv[1:]:
if len(v) > 3:
if v[0:3] == 'COM':
PORTNAME = v
continue
if v.isdigit():
WAITTIMEMS = int(v)
continue
if v in '* % &'.split():
WAIT_LOOP = 1
continue
filebase = v + ".PY"
filename = os.path.join(doppath, filebase)
#------------------------------------------------------------
if not os.path.isfile(filename):
printf("File %s does not exist !"%filename)
exit()
#------------------------------------------------------------
sport = serial.Serial()
sport.baudrate = 115200
sport.timeout = 0.1
try:
sport.port = PORTNAME
except:
printf('Set sport port %s error. '%PORTNAME)
try:
sport.open()
except serial.serialutil.SerialException:
printf('Open sport port %s error.'%PORTNAME)
else:
printf('Open sport port %s Ok.'%PORTNAME)
#------------------------------------------------------------
sport.write(b'\x03') # Terminate the current program
sport.write(b'\x03') # Terminate the current program
time.sleep(.05)
sport.write(b'\x04') # Software reboot PI Pico
sport.timeout = 0.1
printf(sport.read(10000).decode('utf-8'))
sport.timeout = 0.05
sport.write(b'\x05') # Enter Paste mode
printf(sport.read(10000).decode('utf-8'))
#------------------------------------------------------------
lastnullline = 0
lastbyte = b''
with open(filename, 'r') as f:
for l in f.readlines():
keepline = l.replace('\n', '\r')
#----------------------------------------------------
l = l.lstrip(' ')
if len(l) > 0:
if l.find('head') >= 0: continue
if l[0] == '#': continue
if len(l) <= 2:
if lastnullline != 0:
continue
lastnullline = 1
else:
lastnullline = 0
lbyte = bytes(keepline, 'utf-8')
if len(lastbyte) > 0:
sport.write(lastbyte)
lastbyte = lbyte
continue
if len(lastbyte) > 0:
sport.write(lastbyte)
#------------------------------------------------------------
sport.timeout = 0.1
printf(sport.read(10000).decode('utf-8'))
printf('\a')
sport.write(b'\x04') # Exit the paste mode
#------------------------------------------------------------
if WAIT_LOOP != 0:
sport.timeout = 0.05
while True:
key = tspread()
if key[8] == 2 or key[7] == 2:
sport.write(b'\0x3')
sport.write(b'\0x3')
printf('\r\nUser Terminate .\a')
break
readstr = sport.read(10000).decode('utf-8')
if len(readstr) > 0:
tspshowinfor(readstr)
else:
sport.timeout = WAITTIMEMS / 1000.0
printf(sport.read(10000).decode('utf-8'))
#------------------------------------------------------------
#------------------------------------------------------------
# END OF FILE : UPPPP.PY
#============================================================
### <font face=宋体 color=teal>2.测试程序</font>
使得开发板上的LED(PIN25)闪烁。
```python
#!/usr/local/bin/python
# -*- coding: gbk -*-
#============================================================
# TESTMIC.PY -- by Dr. ZhuoQing 2021-02-24
#
# Note:
#============================================================
from head import *
from machine import Pin, Timer
led = Pin(25, Pin.OUT)
tim = Timer()
#------------------------------------------------------------
def tick(timer):
global led
led.toggle()
#--------------------------------------------------------
tim.init(freq=5, mode=Timer.PERIODIC, callback=tick)
for i in range(10):
print(i**2)
print('hello')
#------------------------------------------------------------
# END OF FILE : TESTMIC.PY
#============================================================