使用 Python 管理串口通信:实现一个串口管理器


程序员老茶

🙈作者简介:练习时长两年半的Java up主
🙉个人主页:程序员老茶
🙊 P   S : 点赞是免费的,却可以让写博客的作者开心好久好久😎
📚系列专栏:Java全栈,计算机系列(火速更新中)
💭格   言:种一棵树最好的时间是十年前,其次是现在
🏡动动小手: 点个关注不迷路,感谢宝子们一键三连

课程名:Python

内容/作用:知识点/设计/实验/作业/练习

学习:使用 Python 管理串口通信:实现一个串口管理器

使用 Python 管理串口通信:实现一个串口管理器

在嵌入式系统开发和调试中,串口通信是一项基本技能。本文将介绍如何使用 Python 和 pySerial 库来实现一个简易的串口管理工具。我们将展示一个完整的类来管理串口的打开、关闭和数据传输操作。

代码实现

以下是我们实现的一个名为 SerialPortManager 的类,它提供了打开、关闭串口以及发送 AT 命令的功能。

import serial
import time

class SerialPortManager:
    def __init__(self):
        self.com_port = None
        self.at_commands_sent = []

    def open_port(self, port_name):
        try:
            self.com_port = serial.Serial(port_name, baudrate=9600, bytesize=serial.EIGHTBITS,
                                          stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE,
                                          timeout=1)
            if self.com_port.is_open:
                return "Port opened successfully"
            else:
                return "Error: Port could not be opened"
        except Exception as e:
            return f"Error: {str(e)}"

    def write_to_port(self, at_command):
        try:
            if self.com_port is not None and self.com_port.is_open:
                # 发送ASCII值
                print(f"写入={at_command.encode('ascii').decode('ascii')}")
                self.com_port.write(at_command.encode('ascii'))
                self.com_port.flush()

                # 稍等待响应
                time.sleep(1)

                # 读取返回的数据
                read_buffer = self.com_port.read(1024)

                # 过滤掉非ASCII字符
                data = ''.join(char for char in read_buffer.decode('latin-1') if char.isascii())

                print(f"Received data: {data}")

                self.record_at_command_sent(at_command)
                return data
            else:
                return "Error: Port is not open"
        except Exception as e:
            return f"Error: {str(e)}"

    def close_port(self):
        if self.com_port is not None:
            self.com_port.close()
            self.com_port = None

    @staticmethod
    def convert_hex_array_to_byte_array(hex_array):
        return bytes(int(hex_str, 16) for hex_str in hex_array)

    def record_at_command_sent(self, at_command):
        self.at_commands_sent.append(at_command)

    def get_at_commands_sent(self):
        return self.at_commands_sent

主要功能介绍

  1. 初始化: __init__ 方法初始化类的实例变量。
  2. 打开串口: open_port 方法尝试打开指定的串口,如果成功则返回成功信息,否则返回错误信息。
  3. 写入数据到串口: write_to_port 方法发送 AT 命令并读取响应。
  4. 关闭串口: close_port 方法关闭已打开的串口。
  5. 记录发送的 AT 命令: record_at_command_sent 方法记录已经发送的 AT 命令。
  6. 获取已发送的 AT 命令: get_at_commands_sent 方法返回所有已发送的 AT 命令列表。

菜单操作

我们还实现了一个简单的菜单程序,允许用户通过命令行打开串口、发送命令和关闭串口。

def menu():
    spm = SerialPortManager()
    port_opened = False

    while True:
        print("\n--- Serial Port Menu ---")
        print("1. Open Port")
        print("2. Send Command")
        print("3. Close Port")
        print("4. Exit")

        choice = input("Enter your choice: ")

        if choice == '1':
            if port_opened:
                print("Port is already opened.")
            else:
                port_name = input("Enter port name (e.g., COM3): ")
                result = spm.open_port(port_name)
                print(result)
                if "successfully" in result:
                    port_opened = True

        elif choice == '2':
            if not port_opened:
                print("Please open the port first.")
            else:
                command = input("Enter command to send: ")
                response = spm.write_to_port(command)
                print("Response: ", response)

        elif choice == '3':
            if not port_opened:
                print("Port is not open.")
            else:
                spm.close_port()
                print("Port closed successfully.")
                port_opened = False

        elif choice == '4':
            if port_opened:
                spm.close_port()
                print("Port closed successfully.")
            print("Exiting...")
            break

        else:
            print("Invalid choice. Please try again.")

# 用法示例
if __name__ == "__main__":
    menu()

运行示例

  1. 打开串口: 提示用户输入串口名称(例如 COM3),并尝试打开。
  2. 发送命令: 用户可以输入 AT 命令,程序将发送命令并打印响应。
  3. 关闭串口: 关闭当前打开的串口。
  4. 退出程序: 关闭串口并退出程序。

通过以上代码,我们实现了一个基本的串口管理工具,能够帮助开发者进行串口通信的测试和调试。希望这篇博客能为你的开发工作带来帮助!

总结

   感谢小伙伴们一键三连,咱们下期文章再见~


往期精选

第1集:SpringCloud:认识微服务
第2集:SpringCloud:服务拆分和远程调用
第3集:SpringCloud:Eureka注册中心


往 期 专 栏
Java全栈开发
数据结构与算法
计算机组成原理
操作系统
数据库系统
物联网控制原理与技术
  • 20
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员老茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值