Interpolate Between Elements In An Array Of Floats
I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the a
Solution 1:
do you think about something like that?
import time
l = [1.222, 3.111, 0.456, 9.222, 22.333]
defplay_led(value):
#here should be the led- codeprint value
defcalc_ramp(given_list, interval_count):
new_list = []
len_list = len(given_list)
for i inrange(len_list):
first = given_list[i]
second = given_list[(i+1) % len_list]
delta = (second - first) / interval_count
for j inrange(interval_count):
new_list.append(first + j * delta)
return new_list
defendless_play_led(ramp_list,count):
endless = count == 0
count = abs(count)
while endless or count!=0:
for i inrange(len(ramp_list)):
play_led(ramp_list[i])
#time.sleep(1)ifnot endless:
count -= 1print'##############',count
endless_play_led(calc_ramp(l, 3),2)
endless_play_led(calc_ramp(l, 3),-2)
endless_play_led(calc_ramp(l, 3),0)
Solution 2:
another version, similar to the version of dsgdfg (based on his/her idea), but without timing lag:
import time
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333]
defplay_LED(value):
s = ''for i inrange(int(value*4)):
s += '*'print s, value
definterpol(first, second, fract):
return first + (second - first)*fract
deffind_borders(list_of_values, total_time, time_per_step):
len_list = len(list_of_values)
total_steps = total_time // time_per_step
fract = (total_time - total_steps * time_per_step) / float(time_per_step)
index1 = int(total_steps % len_list)
return [list_of_values[index1], list_of_values[(index1 + 1) % len_list], fract]
defstart_program(list_of_values, time_per_step, relax_time):
total_start = time.time()
whileTrue:
last_time = time.time()
while time.time() - last_time < relax_time:
pass
x = find_borders(list_of_values,time.time(),time_per_step)
play_LED(interpol(x[0],x[1],x[2]))
start_program(list_of_ramp,time_per_step=5,relax_time=0.5)
Post a Comment for "Interpolate Between Elements In An Array Of Floats"