pySerial 的多进程好例子

0 投票
2 回答
6187 浏览
提问于 2025-04-17 01:38

有没有地方可以让我看看在Python的多进程环境中执行pySerial操作的例子?

===对上述问题的更新===

这是Arduino的代码:

//Initialize the pins

void setup()
{
    //Start serial communication
}

void loop()
{
    //Keep polling to see if any input is present at the serial PORT
    //If present perform the action specified.
    //In my case : TURN ON the led or TURN OFF.
}

同样,这是Python前端的代码:

作为基本参考,我使用了无痛并发:多进程模块,(PDF,3.0 MB)。

#import the different modules like time,multiprocessing
#Define the two parallel processes:
def f1(sequence):
    #open the serial port and perform the task of controlling the led's
    #As mentioned in the answer to the above question : Turn ON or OFF as required
    #The 10 seconds ON, then the 10 seconds OFF,finally the 10 seconds ON.

def f2(sequence):
    #Perform the task of turning the LED's off every 2 seconds as mentioned.
    #To do this copy the present conditions of the led.
    #Turn off the led.
    #Turn it back to the saved condition.

def main():
    print "Starting main program"

    hilo1 = multiprocessing.Process(target=f1, args=(sequence))
    hilo2 = multiprocessing.Process(target=f2, args=(sequence))

    print "Launching threads"
    hilo1.start()
    hilo2.start()
    hilo1.join()
    hilo2.join()
    print "Done"

if ____name____ == '____main____':
    main()

在执行上述操作时,我遇到了一些问题:

  1. 进程f1按要求执行任务。也就是说,它会让LED亮10秒,然后熄灭10秒,最后再亮10秒。看起来进程f2根本没有执行(也就是说,LED每两秒熄灭一次),尽管程序成功结束。这可能是什么原因呢?

  2. 如果我在进程中使用print打印一些东西,它不会出现在屏幕上。我很好奇那些提到例子的人是如何显示进程打印输出的。

2 个回答

-1

好吧,这里有一个代码示例,展示了如何在一个图形界面应用程序(使用PyQt)中,利用PySerial进行监控,而且这个监控是在一个单独的线程中运行的。

0

你为什么要用 join 呢?因为 join 会让调用它的线程停下来,直到被调用的那个进程结束,或者等到你设定的超时时间到了。
所以你的 f2 没法开始执行,因为 f1 还在运行。

试试把这段代码放在 main 里运行:

procs = []
procs.append(Process(target=f1, args=(sequence))
procs.append(Process(target=f2, args=(sequence))
map(lambda x: x.start(), procs)
map(lambda x: x.join(), procs)

撰写回答