Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1584

Python • Creating Separate PWM Objects in Multiple Threads

$
0
0
Hello, All.

I'm wondering how one might go about creating a single PWM object in multiple threads, as to prevent multiple threads from attempting to access the same PWM object at the same time. This would obviously throw an error.

Say I have the following setup:

Code:

GPIO.setup(pin1, GPIO.OUT, initial=GPIO.LOW)GPIO.setup(pin2, GPIO.OUT, initial=GPIO.LOW)
Now if I have the following function:

Code:

def power(pin, level, duration):        output = GPIO.PWM(pin, 1000)        output.start(level)        sleep(duration)        output.stop()
If I call this function in main() as follows, there is no issue:

Code:

power(pin1, 50, 5) # Pin1 at 50% duty-cycle for 5 seconds
However, let's say I have a list of GPIO values (ie, pin, duty-cycle & duration) and want to run some of them congruently instead of sequentially, how might I do that?

I have the following (with some minor changes) in main:

Code:

threads = []for i in range(len(myList)):        t = threading.Thread(target=power, args=(device, level, duration)        threads.append(t)for i in range(len(myList):        threads[i].start()        sleep(someDelay)) # This is the time (in my list) to wait until the next GPIO is powered on. If it's zero, that means do not wait for the previous thread to finish.for i in range(len(myList)):        threads[i].join()
This works, as long as the length of "someDelay" is longer than "duration". And this makes sense as if a new thread spins up, both threads are going to be attempting to use the pwm object, "output", as created in my power() function. The question is, how can I create a new PWM objects within the power() function so that these threads don't step on each other?

Please let me know if any additional information is required to help in understanding my problem.

Best,
Joe

Statistics: Posted by joebro391 — Wed Mar 26, 2025 8:26 pm



Viewing all articles
Browse latest Browse all 1584

Trending Articles