Python 串口读写的实现方法

1.安装pyserial

https://pypi.python.org/pypi/pyserial

Doc:http://pythonhosted.org/pyserial/

使用Python Package Index (PyPi)

pip install pyserial-3.1.1-py2.py3-none-any.whl

2. Demo

import serial
from time import sleep

def recv(serial):
  while True:
    data = serial.read_all()
    if data == '':
      continue
    else:
      break
    sleep(0.02)
  return data

if __name__ == '__main__':
  serial = serial.Serial('COM5', 9600, timeout=0.5) #/dev/ttyUSB0
  if serial.isOpen() :
    print("open success")
  else :
    print("open failed")

  while True:
    data =recv(serial)
    if data != b'' :
      print("receive : ",data)
      serial.write(data) #数据写回

3.结果

Python 串口读写的实现方法