SoFunction
Updated on 2024-11-13

Python Serial serial port basic operation (send and receive data)

1, need modules and test tools

Module name: pyserial

Download with the command: python -m pip install pyserial

Serial debugging tool: sscom5.13.

2、Import Module

import serial

3. Open the serial port

It can be opened directly by creating an instance of Serial().

Return Example

# encoding=utf-8
import serial
if __name__ == '__main__':
  com = ('COM3', 115200)
  print com

running result

Serial<id=0x3518940, open=True>(port='COM3', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)

4、Send data

Function name write()

The return value is the number of bytes sent successfully

# encoding=utf-8
import serial
if __name__ == '__main__':
  com = ('COM3', 115200)
  success_bytes = ('This is data for test')
  print success_bytes

running result

21

Serial Tools Interface

5. Receiving data (receiving fixed-length data)

The function is called read(size=1)

Characters received in size units are blocked and wait to be received until they are received, unless a timeout is set (this example is not set)

# encoding=utf-8
import serial
if __name__ == '__main__':
  com = ('COM3', 115200)
  data = (10)
  print data

running result

123456789a

Serial Tools Interface

6. Receive data (always receive within the timeout period)

The function is called read(size=1)

The parameter is the length of the received string, default is 1, usually pass inWaiting(), it means monitoring the length of the received string.

With While you can always receive

# encoding=utf-8
import serial
import time

if __name__ == '__main__':
  com = ('COM3', 115200)
  over_time = 30
  start_time = ()
  while True:
    end_time = ()
    if end_time - start_time < over_time:
      data = (())
      data = str(data)
      if data != '':
        print data

running result

111
222
aaa
bbb
1a2b3c4d

Serial Tools Interface

7. Encapsulation into classes

# -*- encoding=utf-8 -*-
import serial
import time

import WriteLog


class COM:
  def __init__(self, port, baud):
     = port
     = int(baud)
    self.open_com = None
     = ('ITC_LOG.LOG')
    self.get_data_flag = True
    self.real_time_data = ''

  # return real time data form com
  def get_real_time_data(self):
    return self.real_time_data

  def clear_real_time_data(self):
    self.real_time_data = ''

  # set flag to receive data or not
  def set_get_data_flag(self, get_data_flag):
    self.get_data_flag = get_data_flag

  def open(self):
    try:
      self.open_com = (, )
    except Exception as e:
      ('Open com fail:{}/{}'.format(, ))
      ('Exception:{}'.format(e))

  def close(self):
    if self.open_com is not None and self.open_com.isOpen:
      self.open_com.close()

  def send_data(self, data):
    if self.open_com is None:
      ()
    success_bytes = self.open_com.write(('UTF-8'))
    return success_bytes

  def get_data(self, over_time=30):
    all_data = ''
    if self.open_com is None:
      ()
    start_time = ()
    while True:
      end_time = ()
      if end_time - start_time < over_time and self.get_data_flag:
        data = self.open_com.read(self.open_com.inWaiting())
        # data = self.open_com.read() # read 1 size
        data = str(data)
        if data != '':
          ('Get data is:{}'.format(data))
          all_data = all_data + data
          print data
          self.real_time_data = all_data
      else:
        self.set_get_data_flag(True)
        break
    return all_data
if __name__ == '__main__':
  pass
  com = COM('com3', 115200)
  # ()
  print com.send_data('data')
  com.get_data(50)
  ()

8, for the primary function description (Baidu see, did not test)

readall(): read all characters, is blocking, unless the received string ends in EOF or exceeds the buffer, the function will not return. Generally, you need to set the timeout parameter of the serial port.

Readline(): read a line, end with /n, if there is no /n, keep reading, blocking.

This is the whole content of this article.