串口

野火K210 AI视觉相机 可以使用28pin IO接口配置两个串口设备,串口的波特率可达5Mbps

野火logo 野火logo

如上图IO引脚图,可以随意使用任意IO作为uart_tx 和 uart_rx 串口的电平是3.3V的,如果接5V的引脚需要调整电路再连接。

下面使用 IO_1IO_0 这两个引脚分别复用成 UART1_TXUART1_RX

其他引脚也可以复用成 UART1_TXUART1_RX ,需要自行修改配置。

UART2的配置方法也和UART1类似,修改相应名字即可。

例程讲解

该例程在 例程的 02-Hardware\uart.py ,可以在 CanMV IDE 中打开

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from board import board_info
from fpioa_manager import fm
from maix import GPIO
import time
from machine import UART
import _thread

fm.register(1, fm.fpioa.UART1_TX)
fm.register(0, fm.fpioa.UART1_RX)

# 构造UART对象
uart1 = UART(UART.UART1, 115200)

def uart_rev_func(name):
    while 1:
        if uart1.any() != 0:
            rev = uart1.read()
            print("UART get rev:", rev.decode())

_thread.start_new_thread(uart_rev_func,("uart_rev",))
while True:
    uart1.write("Send from UART!")
    time.sleep(1)

实验准备

  1. 野火K210 AI视觉相机 连接到 CanMV IDE

  2. 将28pin引脚中的 IO_1 连接到串口模块的 RX

  3. 将28pin引脚中的 IO_0 连接到串口模块的 TX

  4. 将28pin引脚中的 GND 连接到串口模块的 GND

  5. 将串口模块的波特率设置为 115200

  6. 执行程序

运行结果

1.运行之后, 每隔一秒就会发送 Send from UART! 到串口模块上。

2.与此同时,程序还设置了一个线程,当串口模块发送数据时,会将串口模块的数据打印到串口终端上。

程序分析

1
2
3
4
5
6
from board import board_info
from fpioa_manager import fm
from maix import GPIO
import time
from machine import UART
import _thread
  • 导入模块 board fpioa_manager maix time machine _thread

1
2
3
4
5
fm.register(1, fm.fpioa.UART1_TX)
fm.register(0, fm.fpioa.UART1_RX)

# 构造UART对象
uart1 = UART(UART.UART1, 115200)
  • 配置 IO_1 引脚为 UART1_TX

  • 配置 IO_0 引脚为 UART1_RX

  • 创建一个UART对象uart1,配置为使用UART1接口,波特率为115200

1
2
3
4
5
6
7
def uart_rev_func(name):
    while 1:
        if uart1.any() != 0:
            rev = uart1.read()
            print("UART get rev:", rev.decode())

_thread.start_new_thread(uart_rev_func,("uart_rev",))
  • uart_rev_func(name) :这是一个线程函数,用于接收UART数据。

  • if uart1.any() != 0: :如果UART有数据可读。

  • data = uart1.read() :读取数据。

  • print("UART1 get data:", data.decode()) :将接收到的数据解码并打印。

1
2
3
while True:
    uart1.write("Send from UART!")
    time.sleep(1)
  • uart1.write("From UART1!") :向UART发送字符串“From UART1!”