2016-10-18 26 views
0

我收到了5個浮點的列表,我想用它們作爲值將pwm發送到LED。我想在陣列中的元素之間以可變的毫秒數平滑地上升。浮點數組中的元素之間的插值

因此,如果這是我的數組...

list = [1.222, 3.111, 0.456, 9.222, 22.333] 

我想從斜坡到1.222 3.111在說3000毫秒,然後從3.111到0.456在相同的時間,並且當它到達列表的結尾我希望列表的第5個元素上升到列表的第1個元素並無限期地繼續。

+0

除以時候你」的數量這兩個數的差重新更新LED。然後在每次發送時將該差異添加到第一個值中。這是小學算術。 – Barmar

回答

0

你覺得那樣嗎?

import time 
l = [1.222, 3.111, 0.456, 9.222, 22.333] 

def play_led(value): 
    #here should be the led- code 
    print value 

def calc_ramp(given_list, interval_count): 
    new_list = [] 
    len_list = len(given_list) 
    for i in range(len_list): 
     first = given_list[i] 
     second = given_list[(i+1) % len_list] 
     delta = (second - first)/interval_count 
     for j in range(interval_count): 
      new_list.append(first + j * delta) 
    return new_list 

def endless_play_led(ramp_list,count): 
    endless = count == 0 
    count = abs(count) 

    while endless or count!=0: 
     for i in range(len(ramp_list)): 
      play_led(ramp_list[i]) 
      #time.sleep(1) 
     if not endless: 
      count -= 1 
     print '##############',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) 
+0

如果不使用ABS和WISE,則需要保存每個值。要求比較step_up或step_down的每個值。你有沒有看到用於保存當前值的變量? – dsgdfg

+0

需要使用'_clk'來進行通信或微控制器的響應時間,'_sensitvy'爲所有處理工作設定時間而沒有錯誤。 – dsgdfg

+0

@dsgdfg:爲什麼(ABS/WISE)?您將Delta分解爲符號和值,並且唯一使用它的地方是將產品添加到_from時。如果你不想分裂它將是一樣的。 – am2

0

另一個版本,類似於dsgdfg的版本(基於他/她的想法),但沒有時間滯後:

import time 
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333] 

def play_LED(value): 
    s = '' 
    for i in range(int(value*4)): 
     s += '*'   
    print s, value 

def interpol(first, second, fract): 
    return first + (second - first)*fract 

def find_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] 

def start_program(list_of_values, time_per_step, relax_time): 
    total_start = time.time() 
    while True: 
     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) 
相關問題