为了通过python编程控制串口发送数据给单片机,编写此程序
- # !/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- # ============================================================
- # @Date : 2022/05/16 21:50:12
- # @Author : miles
- # @Email : lishan@st.xatu.edu.cn
- # @File : serial_demo.py
- # @IDE : PyCharm
- # @Func : Describes the function of the file
- # ============================================================
- """
- import time
-
- import serial.tools.list_ports
-
- if __name__ == '__main__':
- # 读取串口列表
- ports_list = list(serial.tools.list_ports.comports())
- if len(ports_list) <= 0:
- print("无串口设备")
- else:
- print("可用的串口设备如下: ")
- print("num\t\tname\t\t\t\t\t\tnumber")
- for i in range(len(ports_list)):
- comport = list(ports_list[i])
- comport_number, comport_name = comport[0], comport[1]
- print("%s\t\t%s\t\t%s" % (i, comport_name, comport_number))
-
- # 打开串口
- port_num = ports_list[0][0]
- print("默认选择串口: %s" % port_num)
- # 串口号: COM3, 波特率: 115200, 数据位: 7, 停止位: 2, 超时时间: 0.5秒
- ser = serial.Serial(port=port_num, baudrate=115200, bytesize=serial.SEVENBITS, stopbits=serial.STOPBITS_TWO,
- timeout=0.5)
- if ser.isOpen():
- print("打开串口成功, 串口号: %s" % ser.name)
- else:
- print("打开串口失败")
-
- # 串口发送数据
- data = "%d:%d" % (130, 1)
- print("发送数据: %s" % data)
- write_len = ser.write(data.encode('utf-8'))
- print("串口发出{}个字节".format(write_len))
-
- # 读取串口输入信息并输出
- while True:
- t = time.time()
- print("\r%.2f 等待串口接收数据......" % t, end="")
- com_input = ser.read(10)
- if com_input:
- print(com_input)
- break
-
- # 关闭串口
- ser.close()
- if ser.isOpen():
- print("串口未关闭")
- else:
- print("串口已关闭")
