用MicroPython玩Newbit(六)-- neopixle

原创
2017/05/12 21:37
阅读数 4.5K

microbit/newbit的MicroPython固件中,内置了neopixel彩灯的控制,我们可以使用任意一个GPIO去控制neopixel,支持任意数量的彩灯。

import neopixel

np = neopixel.NeoPixel(pin1, 8)
np[0] = (0, 0, 200)
np[1] = (0, 50, 100)
np[2] = (200, 0, 0)
np.show()

函数 neopixel.NeoPixel(PIN, NUM) 用来创建 neopixel 对象,它有两个参数,第一个是GPIO,第二个是彩灯的数量。

neopixel 对象是一个元组列表,每个列表项都是由 RGB 三种颜色组成的元组。RGB参数的范围是 0-255,三种颜色组合起来就有 256 x 256 x 256 = 1.67M种颜色。

颜色参数写入列表后并不能改变彩灯,还需要调用函数 show(),才会更新。如果要清除彩灯,可以调用函数 clear().

官方的例子,随机显示彩灯。

"""
    neopixel_random.py

    Repeatedly displays random colours onto the LED strip.
    This example requires a strip of 8 Neopixels (WS2812) connected to pin0.

"""
from microbit import *
import neopixel
from random import randint

# Setup the Neopixel strip on pin0 with a length of 8 pixels
np = neopixel.NeoPixel(pin0, 8)

while True:
    #Iterate over each LED in the strip

    for pixel_id in range(0, len(np)):
        red = randint(0, 60)
        green = randint(0, 60)
        blue = randint(0, 60)

        # Assign the current LED a random red, green and blue value between 0 and 60
        np[pixel_id] = (red, green, blue)

        # Display the current pixel data on the Neopixel strip
        np.show()
        sleep(100)

 

图形化编程
 

对应的mpy代码:
 

import neopixel
import random
from microbit import *


np = neopixel.NeoPixel(pin0, 8)
while True:
  np[(random.randint(0, 7))] = ((random.randint(1, 50)), (random.randint(1, 50)), (random.randint(1, 50)))
  np.show()
  sleep(100)


如果直接用 microbit/newbit的3.3V供电,注意不要控制太多LED,因为LDO的输出功率有限,很容易造成过热保护。超过8个LED最好就用外部电源。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部