2024年1月28日 星期日

micro:bit -悟空板(WuKong):NeoPixel測試 (Python版)

範例一:分別以紅色、綠色、藍色、白色點亮悟空板上的四顆燈 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)


# Code in a 'while True:' loop repeats forever
while True:
    np[0] = (255, 0, 0)
    np[1] = (0, 255, 0)
    np[2] = (0, 0, 255)
    np[3] = (255, 255, 255)
    np.show()

執行結果:

範例二:同範例一,顯示資料用串列變數來儲存

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)

leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    np[0] = leds[0]
    np[1] = leds[1]
    np[2] = leds[2]
    np[3] = leds[3]
    np.show()

執行結果同上題

範列三:每隔0.5秒燈色旋轉

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)
i = 0
leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    np[0] = leds[i]
    np[1] = leds[(i+1)%4]
    np[2] = leds[(i+2)%4]
    np[3] = leds[(i+3)%4]
    np.show()
    sleep(500)
    i=(i+1)%4

執行結果:


範例四、用迴圈改寫程式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Imports go at the top
from microbit import *
import neopixel
np = neopixel.NeoPixel(pin16, 4)
i = 0
leds=[(255,0,0), (0,255,0), (0,0,255), (255,255,255)]
# Code in a 'while True:' loop repeats forever
while True:
    for j in range(4):
        np[j] = leds[(i+j)%4]
    np.show()
    sleep(500)
    i=(i+1)%4

執行結果:
同範例三

沒有留言:

張貼留言