I am wanting to get a Blinkt to flash in a specific continuous pattern depending on a message received over MQTT.
Is there a simple way that I am missing in Python to get it to run the appropriate pattern in the background and free up the on_message function to listen for other commands? I am just trying to avoid threads if at all possible…
I would post code, but mine is effectively just the example code from the paho_mqtt/blinkt example at the moment.
Ta!
Dan
You should use a single global variable in which to store the pattern you want to play, then change it in on_message
by using global current_pattern
and then setting it as normal depending upon your message.
Now, replace client.loop_forever()
with:
client.loop_start()
try:
while True:
if current_pattern == "mongoose":
# Do the mongoose pattern!
except KeyboardInterrupt:
client.loop_stop()
(Note: this will use a thread, but it’s not one you have to worry about :D )
You will probably want to use time.time()
to delta time your pattern sequencing, so you don’t block your while
loop. There are quite a few ways of doing that, which we could approach once you’ve got the first step up and running if you like :D
Ahhh, thanks for that. I didn’t know about loop_start() - that’s useful!
I only started playing this morning so the pattern is pretty basic - just solid colours fading in and out in a series of loops. I do need to get other patterns cooked up pretty soon though because it’s going to end up on the wall of my classroom in a couple of weeks and if I learnt anything from my unicorn hat experience last year, it’s that teenagers are fixated by shiny colours!