Problems with reading analog values with pyfirmata on two Arduino Mega's

Viewed 479

For my project I need to read multiple analog pins on two Arduino Mega's. Other tasks like PWM are working perfectly well but when reading analog Pins I can only read values from one of the boards. The others show None:
A0 Board 1: 0.5601

A0 Board 2: None

If I'm using only one board both of them are reading the correct values but together one shows always none.

Here is a simple code to test it:

from pyfirmata.util import Iterator
import time
import threading
from pyfirmata import ArduinoMega


def read_1():
    board1 = ArduinoMega("COM9")
    iterator = Iterator(board1)
    iterator.start()
    analog_0_board1 = board1.get_pin("a:0:i")
    while True:
        time.sleep(0.5)
        a = analog_0_board1.read()
        print("A0 Board 1: " + str(a))


def read_2():
    board2 = ArduinoMega("COM4")
    iterator = Iterator(board2)
    iterator.start()
    analog_0_board2 = board2.get_pin("a:0:i")
    while True:
        time.sleep(0.5)
        b = analog_0_board2.read()
        print("A0 Board 2: " + str(b))


x = threading.Thread(target=read_1)
x.start()

y = threading.Thread(target=read_2)
y.start()

I've read about multiprocessing could fix the problem but I don't know how to use it correctly with pyfirmata, while true loops and tkinter.

Best regards and thanks advance

1 Answers

I managed to solve the problem and maybe my current code can help other people. Instead of the threading part I wrote the following code:

if __name__ == "__main__":
    x = multiprocessing.Process(target=read_1)
    x.start()

    y = multiprocessing.Process(target=read_2)
    y.start()
    root.mainloop()

The root.mainloop() is just to test if tkinter is also possible.

Related