python串口操作_Python串口操作库pyserial(1)

测试过程中需要用到串口,目前采用pyserial库。

1 采用命令行安装pyserial库: pip install pyserial

import sys

import glob

import serial

def serial_ports():

""" Lists serial port names:raises EnvironmentError:On unsupported or unknown platforms:returns:A list of the serial ports available on the system"""

if sys.platform.startswith('win'):

ports = ['COM%s' % (i + 1) for i in range(256)]

elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):

# this excludes your current terminal "/dev/tty"

ports = glob.glob('/dev/tty[A-Za-z]*')

elif sys.platform.startswith('darwin'):

ports = glob.glob('/dev/tty.*')

else:

raise EnvironmentError('Unsupported platform')

result = []

for port in ports:

try:

s = serial.Serial(port)

s.close()

result.append(port)

except (OSError, serial.SerialException):

pass

return result

if __name__ == '__main__':

print(serial_ports())

3 进行串口通讯:

def send_str(port, baudrate, parity, value):

port_set = serial.Serial(port=port, baudrate=baudrate, parity=parity)

port_set.write(value)

# delay 100ms if receive is blank, just waiting 5s.

n = 0

while port_set.inWaiting() == 0:

time.sleep(0.1)

n = n + 1

if n > 50:

# send frame again

port_set.write(value)

break

# every 100ms check the data receive is ready

byte_number_1 = 0

byte_number_2 = 1

while byte_number_1 != byte_number_2:

byte_number_1 = port_set.inWaiting()

time.sleep(0.1)

byte_number_2 = port_set.inWaiting()

receive_frame = port_set.read_all()

return receive_frame

port: 串口号,str格式,例如‘COM3’;

baudrate: 波特率,str格式,例如‘9600’;

parity:校验位,str格式。只需要第一个字母,‘N’无校验,‘O’奇校验,‘E’偶校验;

value: 设置的数据,数据需要为int格式,多字节传输采用list。

# delay 100ms if receive is blank, just waiting 5s.

n = 0

while port_set.inWaiting() == 0:

time.sleep(0.1)

n = n + 1

if n > 50:

# send frame again

port_set.write(value)

break

inWaiting()返回接收到的字符。

此段代码判断是否有数据返回。最多等待5s,之后重发。

# every 100ms check the data receive is ready

byte_number_1 = 0

byte_number_2 = 1

while byte_number_1 != byte_number_2:

byte_number_1 = port_set.inWaiting()

time.sleep(0.1)

byte_number_2 = port_set.inWaiting()

此段代码判断是否接收完成。每100ms判断一次,判断时间可以根据波特率进行修改。

receive_frame = port_set.read_all()

接收全部返回数据。返回数据类型为byte,可以采用与list相同方法进行操作。

4 判断端口是否可用

def serial_alive(port=None):

port_status = True

try:

s = serial.Serial(port)

s.close()

except OSError:

port_status = False

return port_status

if __name__ == '__main__':

print(serial_alive('COM5'))

你可能感兴趣的:(python串口操作)