Mustak U
Mustak U

Reputation: 113

multiprocessing with serial port

I've a target board which sends me CPU load for every 1sec which communicates through serial port. I want to write a python code which reads data from serial port for every 1sec second and writes to a file and also it should check for user input i.e. if user enters command it should pass that command to target board.

Upvotes: 2

Views: 1661

Answers (1)

EvenLisle
EvenLisle

Reputation: 4812

You can create two threads, one listening for user input, the other polling the serial port every second. Check out threading for information on multithreading in python and pyserial for information on reading from serial ports. The threading package provides your desired repetition functionality: https://docs.python.org/2/library/threading.html#timer-objects

[EDIT]

Sample code, obviously replace /dev/ttyS1 with the desired port and do something useful with the user input:

import serial
import threading
def read_from_serial():
  # port = "/dev/ttyS1"
  # ser = serial.Serial(port, 19200, timeout = 1)
  # print ser.readline()
  # ser.close()
  print "read"
  threading.Timer(1, read_from_serial).start()


if __name__ == "__main__":
  serial_thread = threading.Thread(target = read_from_serial())
  serial_thread.start()
  while True:
    print raw_input("User input: ")

Upvotes: 3

Related Questions