2

I'm trying to make a raspberry pi control an addressable LED strip using a webserver. Because I can't port forward, the webserver is hosted on python anywhere and the pi is constantly sending get requests to see if it needs to change the lighting.

Certain lighting effects will have their own timings and will need to loop on their own, like a rainbow effect for instance which will loop and update the LED colours at 10Hz. How can I have a script updating the LED colours while it also has to send the get requests? The get requests are relatively slow, so putting them in the same loop doesn't seem like a viable option.

Edit: Thanks for the responses. Turns out I was looking for asynchronous programming.

2
  • 1
    multi threading or multiprocessing. Commented Mar 23, 2022 at 2:26
  • 2
    Async/await/aiohttp Commented Mar 23, 2022 at 2:29

1 Answer 1

3

You can do this pretty simply with asyncio. Do note that for doing web requests you should also use an async library like aiohttp. Otherwise the blocking http call will delay the other task from running.

Here's an example where you use a context object to allow sharing data between the different tasks. Both tasks will need to have some await calls in them which is what allows asyncio to switch between the running tasks to achieve concurrency.

import asyncio

class Context:
    def __init__(self):
        self.message = 0

async def report(context):
    while True:
        print(context.message)
        await asyncio.sleep(1)

async def update(context):
    while True:
        context.message += 1
        await asyncio.sleep(3)

async def main():
    context = Context()
    await asyncio.gather(report(context), update(context))

if __name__ == "__main__":
    asyncio.run(main())
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect thanks for the help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.