I'm creating a python program for the raspberry pi using the GPIO library and using it to control LEDs to blink to music. Im having trouble keeping the blinking and the music in sync though. My current code:
for wval, bval, gval, yval, rval in data_gen:
set_leds(whites, wval)
set_leds(blues, bval)
set_leds(greens, gval)
set_leds(yellows, yval)
set_leds(reds, rval)
sleep(GRAPH_TIME)
In this code,
- GRAPH_TIME is the refresh rate of the LEDs in seconds. Currently set to 0.01, giving me 100hz refresh rate.
- data_gen is a nx5x3 array, with n being the length of the song in seconds divided by GRAPH_TIME.the 5x3 represents 5 colors and 3 LEDs per color. Each entry is from 0 - 100, representing the value of the LED. These were achieved by splitting the song into n parts and then performing fft on each section and seperating the results to get the values of the LEDs.
- set_leds is a function that sets all LEDs of a certain color to their respective values.
The problem, as you can guess, is that the set_led functions take time to execute and the sleep function is not very accurate. So, since the song is played continuously by an external program, after a minute or so the LEDs and become noticeably offset from the music.
Is there anything in python, perhaps using some sort of multi-threading, that could let me accurately keep the timer running?