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[ ]:
相关推荐
weelinking2 小时前
【2026】08_Claude与版本控制:Git协作技巧
数据库·人工智能·git·python·数据挖掘·交互·cloudera
踩着两条虫7 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB7 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
scan7248 小时前
智能体多个工具调用
python
2401_867623988 小时前
CSS Flex布局中如何设置子元素间距_掌握gap属性的现代用法
jvm·数据库·python
即使再小的船也能远航8 小时前
【Python】安装
开发语言·python
weixin_421725268 小时前
Linux 编程语言全解析:C、C++、Python、Go、Rust 谁更强?
linux·python·go·c·编程语言
Irissgwe8 小时前
类与对象(三)
开发语言·c++·类和对象·友元
没有梦想的咸鱼185-1037-16638 小时前
AI-Python机器学习、深度学习核心技术与前沿应用及OpenClaw、Hermes自动化编程
人工智能·python·深度学习·机器学习·chatgpt·数据挖掘·数据分析
雪度娃娃8 小时前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++