Python读MCU串口

将Jupyter Notebook(.ipynb)文件转换为Python(.py)文件的3种方法_python_脚本之家

python 复制代码
#!/usr/bin/env python
# coding: utf-8

# In[ ]:

import sys
import serial
import threading
from datetime import datetime

input_flag = 0

class UART(object):
    def __init__(self,port,baud):
#         print("初始化")
        self.err = 0
        try:
            self.serial = serial.Serial(port,baud)
            print("串口连接成功")
        except:
            print("串口连接失败")
            self.err =  -1;
    def uart_rev_wait(self):
        print("开始接收")
#         串口接收
        while(True):
            try:
                rev_data = self.serial.readline()
#                 text = "当前时间"
                now = datetime.now()
                formatted_str = now.strftime('%Y-%m-%d %H:%M:%S')
                data = formatted_str +"------"+ "串口数据:"+ rev_data.decode();
#         print("DEV_NUM:"+port)
                print(data)
            except:
                print("接收数据失败")
        
    def uart_rev_start(self):
        print("创建接收线程")
        thread = threading.Thread(target=self.uart_rev_wait,daemon = True)
        thread.start()


if __name__ == '__main__':
#     print("主线程")
    uart0 = UART("COM27",115200)
    if(0==uart0.err):
        print("init UART success")
        uart0.uart_rev_start()
    
    while(True):
#         print("主线程runing")
        if(input_flag == 1):
            break;
        
    print("exit")

# In[ ]:
相关推荐
ikun_文2 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes2 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明2 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn2 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困2 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao4 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼4 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君4 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python
Interview Aid1124 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt11 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#