Skip to content Skip to sidebar Skip to footer

Python Code For Serial Data To Print On Window.

I am quite new to python and pyserial. My pc was installed with python 2.7.4 with pyserial and I want to print the serially received data on a seperate window on my pc. First the

Solution 1:

The problem here is that you have two loops that should be constantly running: The mainloop for the GUI and the loop for transmitting the serial data. What you can do to solve this is to start a new thread to receive the content of the serial port, put it in a Queue, and check periodically in the GUI thread the content of this queue:

import serial
import threading
import time
import Queue
import Tkinter as tk


class SerialThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        s = serial.Serial('/dev/ttyS0',9600)
        s.write(str.encode('*00T%'))
        time.sleep(0.2)
        while True:
            if s.inWaiting():
                text = s.readline(s.inWaiting())
                self.queue.put(text)

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry("1360x750")
        frameLabel = tk.Frame(self, padx=40, pady =40)
        self.text = tk.Text(frameLabel, wrap='word', font='TimesNewRoman 37',
                            bg=self.cget('bg'), relief='flat')
        frameLabel.pack()
        self.text.pack()
        self.queue = Queue.Queue()
        thread = SerialThread(self.queue)
        thread.start()
        self.process_serial()

    def process_serial(self):
        value=True
        while self.queue.qsize():
            try:
                new=self.queue.get()
                if value:
                 self.text.delete(1.0, 'end')
                value=False
                 self.text.insert('end',new)
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

app = App()
app.mainloop()

This code is tested with my Pi3 ttyS0 serial port and serially connected PC and slave device: its 100% working with single device connected serially


Post a Comment for "Python Code For Serial Data To Print On Window."