0
votes

I have a python program using serial port to connect with Arduino. I want to plot some data in real time without slowing down the execution, so I try multiprocessing. However, I got the error

    serial.serialutil.SerialException: could not open port 'COM6': WindowsError(5, 'Access is denied.') # COM6 is the port connected to Arduino

Surprisingly, the connection between Arduino is still alive while the function in multiprocessing is not running. My code is as follows,

class ArduinoThread(threading.Thread):
    def __init__(self, portnum):
        threading.Thread.__init__(self)
        self.setName("Arduino")
        self.Arduino = serial.Serial(port="COM"+str(portnum), baudrate=19200)
    def run(self):
        # some function


def MyPlot_realtime(DATA):
    while True:
        data = DATA.get(False)
        plt.plot(data)


UNO = ArduinoThread(6)
UNO.start()

plt.ion()
pltQ = multiprocessing.Queue()
pltP = multiprocessing.Process(target=MyPlot_realtime, args=(pltQ,))
pltP.start()

while True:
    # some calculation on data
    UNO.update(data)

    if pltQ.empty():
        pltQ.put(data)

Simply commenting the multiprocessing part the code can work well. The error pop out when there is multiprocessing but the UNO.update(data) is still working while MyPlt_realtime is not working at all.

(My code is quite complicated so I simplified it. I am using another serial port to connect another device. I am using Tkinter as well. Hope the problem didn't come from those part)

1

1 Answers

0
votes

Put your main code in an if condition as follows:

if __name__ == '__main__':

I am not sure why, but it solved the problem for me and most examples seem to do it like that as well.