2

When I run this code below, the 2 LED's do not start at the same time. The yellow one starts slightly late. (about less than 0.1 second) Is there something wrong with my code or any suggestions to fix it?

from threading import Thread
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def red():
    x=0
    while x!= 6:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(18, GPIO.OUT)
        print("Red LED on")
        GPIO.output(18,GPIO.HIGH)
        time.sleep(0.24)
        print("Red LED off")
        GPIO.output(18, GPIO.LOW)
        time.sleep(0.24)
        x=x+1
def yellow():
    x=0
    while x!=6:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(23, GPIO.OUT)
        print("Yellow LED on")
        GPIO.output(23,GPIO.HIGH)
        time.sleep(0.24)
        print("Yellow LED off")
        GPIO.output(23, GPIO.LOW)
        time.sleep(0.24)
        x=x+1

t1 = Thread(target = red)
t2 = Thread(target = yellow)

t1.start()
t2.start()
2

There is no reason for the threads to be synchronised. The red one is started first so will probably run first. If the Python interpreter is stalled between the start of the red and yellow thread the actual gap could be much larger than 0.1 seconds.

If you want the LEDs to be synchronised you need to control them both in the same thread.

Does it matter for what you are trying to do?

0

I don't think you need the GPIO.setmode(GPIO.BCM) and GPIO.setwarnings(False) as the first part of either threads loop as you are already setting this at the start. You could also move the two GPIO.setup lines to before you declare the functions as this should only need to be done once too. You might find that speeds up the execution of both threads and removes the delay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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