0

I am using the pyserial python library to read serial data from an Arduino. Polling for new data would require me to implement an update() method that I must call several times a second. This would be slow and CPU intensive even when there is no communication happening.

Is there an OnSerialData() event I can use? A routine that will execute every time new serial data arrives in the buffer? Most other languages I've worked with have an equivalent.

I am fairly unfamiliar with threading but have a feeling it is involved.

Michael Molter
  • 1,206
  • 1
  • 13
  • 34

1 Answers1

1

A standard approach is to use a thread for this.

Something like this should work:

import threading
import serial
import io
import sys

exit_loop = False

def reader_thread(ser):
  while not exit_loop:
    ch = ser.read(1)
    do_something(ch)

def do_something(ch):
  print "got a character:", ch

ser = serial.serial_for_url(...)
thr = threading.Thread(target = reader_thread, args=[ser])
thr.start()

# when ready to shutdown...

exit_loop = True
if hasattr(ser, 'cancel_read'):
  ser.cancel_read()
thr.join()

Also see the serial.threaded module (also contained in the pyserial library.)

ErikR
  • 50,049
  • 6
  • 66
  • 121