使用线程的pyserial的小例子

时间:2016-08-24 15:14:12

标签: python multithreading pyserial

任何人都可以给我一个关于如何使用线程与pyserial通信的小而简单的例子。 我谷歌搜索超过三天,我仍然是非法的,我甚至没有一个工作代码集成他们两个

基本上我的目标是在这种情况下使用线程:

在后台继续进行串行通信,以便从MCU获得一定的价值(比如说A)。

停止获得值A - 然后达到值B ......并再次开始持续获得值A.

您可以在此处找到一些基本代码。

import threading
import time
import sys
import serial
import os
import time

def Task1(ser):

    while 1:

        print "Inside Thread 1"
        ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit
        b = ser.read(7)
        print b.encode('hex')
        print "Thread 1 still going on"
        time.sleep(1)


def Task2(ser):

    print "Inside Thread 2"
    print "I stopped Task 1 to start and execute Thread 2"
    ser.write('x5A\x03\x02\x08\x02\x0F')
    c = ser.read(7)
    print c.encode('hex')
    print "Thread 2 complete"


def Main():
    ser = serial.Serial(3, 11520)
    t1 = threading.Thread(target = Task1, args=[ser])
    t2 = threading.Thread(target = Task2, args=[ser])
    print "Starting Thread 1"
    t1.start()
    print "Starting Thread 2"
    t2.start()

    print "=== exiting ==="

    ser.close()

if __name__ == '__main__':

    Main()

1 个答案:

答案 0 :(得分:0)

Task2声明没有事实依据:

print "I stopped Task 1 to start and execute Thread 2"

您的实现启动一个线程然后立即启动另一个而不停止第一个。这意味着ser.readser.write命令可能会相互干扰。

你可以做的最简单的事情就是引入允许沟通的变量:

import sys
import os
import time
import threading

thread_flag = None


def Report(s):
    print s
    sys.stdout.flush() # helps to ensure messages from different threads appear in the right order

def Stop():
    global thread_flag
    thread_flag = 'stop'

def Task1(ser):

    Report("Inside Thread 1")
    global thread_flag
    thread_flag = 'go'

    while True:

        Report("Thread 1 waiting for permission to read")
        while thread_flag != 'go': time.sleep( 0.001 )

        while thread_flag == 'go':
            Report("Thread 1 is reading")
            #ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit
            #b = ser.read(7)
            #Report(b.encode('hex'))
            time.sleep(1)

        if thread_flag == 'stop': break
        else: thread_flag = 'paused'   # signals that the inner loop is done

    Report("Thread 1 complete")


def Task2(ser):

    Report("Inside Thread 2")

    global thread_flag
    thread_flag = 'pause' # signals Task1 to pause
    while thread_flag != 'paused': time.sleep(0.001) # waits for Task1 inner loop to exit
    Report("I stopped Task 1 to start and execute Thread 2")

    #ser.write('x5A\x03\x02\x08\x02\x0F')
    #c = ser.read(7)
    #Report(c.encode('hex'))

    thread_flag = 'go' # signals Thread 1 to resume
    Report("Thread 2 complete")


def Main():
    ser = None # serial.Serial(3, 11520)
    t1 = threading.Thread(target = Task1, args=[ser])
    t2 = threading.Thread(target = Task2, args=[ser])
    Report("Starting Thread 1")
    t1.start()

    time.sleep(3)
    Report("Starting Thread 2")
    t2.start()


if __name__ == '__main__':

    Main()

该方法使用全局变量,这通常是不受欢迎的。您可以改为将Task1Task2的{​​{1}}和self方法作为属性。

对于任何比这更复杂的线程间通信,您需要调查锁,互斥锁和信号量(例如self.ser