概述
EC600S有两个串口通信口,TX0/RX0;TX2/RX2,分别对应程序中的UART0 - DEBUG PORT和UART2 – MAIN PORT。运行本例程,
需要通过串口线连接开发板的 MAIN 口和PC,在PC上通过串口工具打开 MAIN 口,并向该端口发送数据,即可看到 PC 发送过来的消息。
(可通过串口转usb口,把TX2/RX2分别与转usb口的RX/TX连接到电脑上即可)
"""
运行本例程,需要通过串口线连接开发板的 MAIN 口和PC,在PC上通过串口工具
打开 MAIN 口,并向该端口发送数据,即可看到 PC 发送过来的消息。
"""
import _thread
import utime
import log
from machine import UART
'''
下面两个全局变量是必须有的,用户可以根据自己的实际项目修改下面两个全局变量的值
'''
PROJECT_NAME = "QuecPython_UART_example"
PROJECT_VERSION = "1.0.0"
'''
* 参数1:端口
注:EC100YCN平台与EC600SCN平台,UARTn作用如下
UART0 - DEBUG PORT
UART1 – BT PORT
UART2 – MAIN PORT
UART3 – USB CDC PORT
* 参数2:波特率
* 参数3:data bits (5~8)
* 参数4:Parity (0:NONE 1:EVEN 2:ODD)
* 参数5:stop bits (1~2)
* 参数6:flow control (0: FC_NONE 1:FC_HW)
'''
# 设置日志输出级别
log.basicConfig(level=log.INFO)
uart_log = log.getLogger("UART")
state = 5
def uartWrite():
count = 10
# 配置uart
uart = UART(UART.UART2,460800, 8, 0, 1, 0)
while count:
write_msg = "Hello count={}".format(count)
# 发送数据
uart.write(write_msg)
uart_log.info("Write msg UART.UART2 :{}".format(write_msg))
utime.sleep(1)
count -= 1
uart_log.info("uartWrite end!")
def UartRead():
global state
uart = UART(UART.UART2,460800, 8, 0, 1, 0)
while 1:
# 返回是否有可读取的数据长度
msgLen = uart.any()
# 当有数据时进行读取
if msgLen:
msg = uart.read(msgLen)
uart.write(msg)
# 初始数据是字节类型(bytes),将字节类型数据进行编码
utf8_msg = msg.decode()
# str
uart_log.info("UartRead msg UART.UART2: {}".format(utf8_msg))
# state -= 1
# if state == 0:
# break
else:
continue
def run():
# 创建一个线程来监听接收uart消息
_thread.start_new_thread(UartRead, ())
if __name__ == "__main__":
#uartWrite()
while 1:
run()
# if state:
# pass
# else:
# break
# 运行结果示例
'''
INFO:UART:Write msg :Hello count=8
INFO:UART:Write msg :Hello count=7
INFO:UART:Write msg :Hello count=6
INFO:UART:Write msg :Hello count=5
INFO:UART:Write msg :Hello count=4
INFO:UART:Write msg :Hello count=3
INFO:UART:Write msg :Hello count=2
INFO:UART:Write msg :Hello count=1
INFO:UART:uartWrite end!
INFO:UART:UartRead msg: read msg 1
INFO:UART:UartRead msg: read msg 2
INFO:UART:UartRead msg: read msg 3
'''
脚本模拟串口工具发送代码如下:
import serial
import time
import threading
# 要发送的文件
send_file = r"C:Users5007957Desktopsendsend6.DAT"
recv_file = r"C:Users5007957Desktopsendrecv6.DAT"
ser = serial.Serial("COM3",460800, timeout=0.5)
print(ser)
def recv_thread():
f = open(recv_file, "wb")
while True:
b = ser.read(1024)
if len(b):
print(f"recv_len={len(b)}")
f.write(b)
f.flush()
time.sleep(0.001)
threading.Thread(target=recv_thread).start()
start = time.time()
with open(send_file, "rb") as f:
b = f.read(1024)
while b:
ser.write(b)
b = f.read(1024)
time.sleep(0.024) #有时候文件丢失,可
#以通过增大延时来防止文件丢失
# print("123")
print(f"time={time.time() - start}")
time.sleep(8) #要记得延时,否则会导致还没接收
#完,文件就已经关闭了
ser.flush()
ser.close()
最后
以上就是彩色豆芽为你收集整理的EC600S串口通信的全部内容,希望文章能够帮你解决EC600S串口通信所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复