0

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()
5
  • 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
    Commented Jan 26, 2023 at 23:13
  • i have added the code please provide a solution Commented 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
    Commented 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. Commented Jan 27, 2023 at 3:00
  • 1
    This is off-topic as it is a general programming question.
    – joan
    Commented Jan 27, 2023 at 8:23

1 Answer 1

0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.