• python调用串口发送数据


    为了通过python编程控制串口发送数据给单片机,编写此程序

    1. # !/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. """
    4. # ============================================================
    5. # @Date : 2022/05/16 21:50:12
    6. # @Author : miles
    7. # @Email : lishan@st.xatu.edu.cn
    8. # @File : serial_demo.py
    9. # @IDE : PyCharm
    10. # @Func : Describes the function of the file
    11. # ============================================================
    12. """
    13. import time
    14. import serial.tools.list_ports
    15. if __name__ == '__main__':
    16. # 读取串口列表
    17. ports_list = list(serial.tools.list_ports.comports())
    18. if len(ports_list) <= 0:
    19. print("无串口设备")
    20. else:
    21. print("可用的串口设备如下: ")
    22. print("num\t\tname\t\t\t\t\t\tnumber")
    23. for i in range(len(ports_list)):
    24. comport = list(ports_list[i])
    25. comport_number, comport_name = comport[0], comport[1]
    26. print("%s\t\t%s\t\t%s" % (i, comport_name, comport_number))
    27. # 打开串口
    28. port_num = ports_list[0][0]
    29. print("默认选择串口: %s" % port_num)
    30. # 串口号: COM3, 波特率: 115200, 数据位: 7, 停止位: 2, 超时时间: 0.5秒
    31. ser = serial.Serial(port=port_num, baudrate=115200, bytesize=serial.SEVENBITS, stopbits=serial.STOPBITS_TWO,
    32. timeout=0.5)
    33. if ser.isOpen():
    34. print("打开串口成功, 串口号: %s" % ser.name)
    35. else:
    36. print("打开串口失败")
    37. # 串口发送数据
    38. data = "%d:%d" % (130, 1)
    39. print("发送数据: %s" % data)
    40. write_len = ser.write(data.encode('utf-8'))
    41. print("串口发出{}个字节".format(write_len))
    42. # 读取串口输入信息并输出
    43. while True:
    44. t = time.time()
    45. print("\r%.2f 等待串口接收数据......" % t, end="")
    46. com_input = ser.read(10)
    47. if com_input:
    48. print(com_input)
    49. break
    50. # 关闭串口
    51. ser.close()
    52. if ser.isOpen():
    53. print("串口未关闭")
    54. else:
    55. print("串口已关闭")

     

  • 相关阅读:
    数据库系列:前缀索引和索引长度的取舍
    MFC工具栏按钮点击,响应消息
    Kotlin高阶函数&DSL布局劝退指南
    基于X86的运算板卡加速边缘智能应用
    【算法刷题日记之本手篇】星际密码与数根
    2022年最新海南建筑八大员(材料员)模拟考试试题及答案
    xss原理分析
    黑马点评关键业务流程梳理
    代码的工厂模式
    【二分】Pythagorean Triples—CF1487D
  • 原文地址:https://blog.csdn.net/lishan132/article/details/125537790