An example of Python using pyserial for serial communication

  • 2021-07-09 08:29:22
  • OfStack

Installing pyserial


pip install pyserial

View available ports


# coding:utf-8

import serial.tools.list_ports

plist = list(serial.tools.list_ports.comports())

if len(plist) <= 0:
  print(" No port found !")
else:
  plist_0 = list(plist[0])
  serialName = plist_0[0]
  serialFd = serial.Serial(serialName, 9600, timeout=60)
  print(" Available port name >>>", serialFd.name)

The issued 106-ary system needs to be converted into the following format


#  Sent 106 Binary string 010591F50000F104
cmd = [0x01, 0x05, 0x91, 0xF5, 0x00, 0x00, 0xF1, 0x04]

Serial communication


Windows The lower port is COM*, Ubuntu Below /dev/ttyS0

import serial

class Ser(object):
  def __init__(self):
    #  Open port 
    self.port = serial.Serial(port='COM4', baudrate=9600, bytesize=8, parity='E', stopbits=1, timeout=2)

  #  Complete flow of sending instructions 
  def send_cmd(self, cmd):
    self.port.write(cmd)
    response = self.port.readall()
    response = self.convert_hex(response)
    return response

  #  Turn into 16 Function of binary system 
  def convert_hex(self, string):
    res = []
    result = []
    for item in string:
      res.append(item)
    for i in res:
      result.append(hex(i))
    return result

Related articles: