Python语言串口的操作

1.简介

Python中有专门的串口操作模块pySerial,使用非常简单。

pySerial的资源网址https://pypi.python.org/pypi/pyserial

github资源和一些使用教程的网址:https://github.com/pyserial/pyserial

串口操作文档http://pythonhosted.org/pyserial/


2  pySerial的安装


pip install pyserial

or:

easy_install -U pyserial


3.Python串口操作简单介绍

class serial.Serial

__init__(port=Nonebaudrate=9600bytesize=EIGHTBITSparity=PARITY_NONEstopbits=STOPBITS_ONE

timeout=Nonexonxoff=False,rtscts=Falsewrite_timeout=Nonedsrdtr=Falseinter_byte_timeout=None)

 

port:COM1,COM2,COM3,COM4......如果port设置为0对应的为COM1

baudrate:设置波特率

bytesize:数据位

stopbits:停止位

timeout:超时时间

  • timeout = None: 长时间等待
  • timeout = 0: 不阻塞形式 (读完之后就返回)
  • timeout = x: x秒后超时 (float allowed)

 

Open port at “9600,8,N,1”, no timeout:

>>> importserial
>>> ser= serial.Serial('/dev/ttyUSB0')  # open serial port
>>> print(ser.name)         # check which port was really used
>>> ser.write(b'hello')     # write a string
>>> ser.close()             # close port

Open named port at “19200,8,N,1”, 1s timeout:

>>> with serial.Serial('/dev/ttyS1',19200, timeout=1)as ser:
...     x = ser.read()          # read one byte
...     s = ser.read(10)        # read up to ten bytes (timeout)
...     line = ser.readline()   # read a '\n' terminated line

Open port at “38400,8,E,1”, non blocking HW handshaking:

>>> ser= serial.Serial('COM3',38400, timeout=0,
...                     parity=serial.PARITY_EVEN, rtscts=1)
>>> s= ser.read(100)       # read up to one hundred bytes
...                         # or as much is in the buffer

一个读写的例子

	import serial  
	from time import sleep  
	ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.5)   
	def recv(serial):    
	    while True:    
	        data =serial.read(30)    
	        if data == '':    
	            continue  
	        else:  
	            break  
                sleep(0.02)   
	    return data    
	while True:    
	    data =recv(ser)    
	    ser.write(data) 





 



你可能感兴趣的:(python)