0

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?

Alex Shmakov
  • 115
  • 7
  • 1
    You have to calculate the sleep time so it adapts to the time taken to set the leds. Basically calculate the time until the desired wakeup point and sleep that long. – Klaus D. Jan 23 '16 at 05:46
  • related: [How to run a function periodically in python](http://stackoverflow.com/q/24174924/4279) – jfs Jan 30 '16 at 08:51

1 Answers1

0

To make a thread do this:

import threading

def blabla:
time.sleep (1)

thread = threading.Thread(target=blabla)#set the target to the function we made
thread.start()#start thread
Jakuje
  • 24,773
  • 12
  • 69
  • 75
RPImaniac
  • 3
  • 5