My self-working on encoders of differential drive robot, I need to read the speed and position of wheels using two encoders simultaneously. I have used the threading library in Python even though I started both functions. Only the function initiated first runs while the second doesn't. I am not sure what the cause of this is. Is there anything to be noted while using threading in GPIO pins of Raspberry Pi 3 B? If so, please help and suggest a solution.
from threading import Thread
import RPi.GPIO as GPIO
import time
import datetime
def encoder_right(t1):
...
def encoder_left(t1):
...
t1 = datetime.datetime.now()
Thread1 = Thread(target = encoder_right(t1),daemon = True)
Thread2 = Thread(target = encoder_left(t1),daemon = True)
Thread1.start()
Thread2.start()
Thread1.join()
Thread1.join()
-
Asking a programming question without code is futile. Threading in Python is complex; due to GIL only 1 thread can run python code at a time.Milliways– Milliways2023年01月26日 23:13:08 +00:00Commented Jan 26, 2023 at 23:13
-
i have added the code please provide a solutionDEVAPRASAD S– DEVAPRASAD S2023年01月27日 02:08:10 +00:00Commented Jan 27, 2023 at 2:08
-
It is difficult to understand this code. Do your initialisation ONCE outside your functions. Your functions NEVER exit so join will never do anything. It is unclear WHY you are using threads - surely a callback would be simpler.Milliways– Milliways2023年01月27日 02:54:28 +00:00Commented Jan 27, 2023 at 2:54
-
I have to read the data from encoder lively while my code has to perform other operation,so i used threading here.DEVAPRASAD S– DEVAPRASAD S2023年01月27日 03:00:29 +00:00Commented Jan 27, 2023 at 3:00
-
1This is off-topic as it is a general programming question.joan– joan2023年01月27日 08:23:20 +00:00Commented Jan 27, 2023 at 8:23
1 Answer 1
In both lines you initialize thread object you make a mistake passing whatever your functions return instead of the function itself. So simply replace both lines with:
Thread1 = Thread(target=encoder_right, args=[t1], daemon=True)
Thread2 = Thread(target=encoder_left, args=[t1], daemon=True)