和爷爷一起学Arduino全彩灯带检测代码
下载流行玩全彩灯带。买来灯带总要检测好坏。从GiHub下载了WS2812库,跑其中的示例代码,闪烁非常快,根本看不清楚。而且,耗电非常厉害。用外接电源供电,Arduino板的稳压电路烫得手不能碰。我们修改了程序,同时只是一个灯亮,从一端跑到另一端,再跑回来。这样,用USB供电也可以运行了。#include #ifdef __AVR__ #include // Required for 16 MHz Adafruit Trinket #endif #define PIN 6 #define NUMP 144 Adafruit_NeoPixel pixels(NUMP, PIN, NEO_GRB + NEO_KHZ800); void setup() { // These lines are specifically to support the Adafruit Trinket 5V 16 MHz. // Any other board, you can remove this part (but no harm leaving it): #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000) clock_prescale_set(clock_p_1); #endif // END of Trinket-specific code. pixels.begin(); } int pn = 0; int md = 1; int r = random(0, 200); int g = random(0, 200); int b = random(0, 200); void loop() { pixels.clear(); pixels.setPixelColor(pn, pixels.Color(r, g, b)); pixels.show(); delay(60); pn = pn + md; if(md == 1 && pn == NUMP || md == -1 && pn == 0){ md = -md; r = random(0, 200); g = random(0, 200); b = random(0, 200); } }
跑一条是一种颜色,碰头后又随机变一种色。这样,灯珠里的RGB三个灯芯都检测到了。有问题,一目了然。
我们用的是144灯珠的全彩灯带,如果你的灯珠数不同,譬如60灯珠的,把代码中的"#define NUMP 144"改成"#define NUMP 60"就可以了。
连接的是D6口。改"#define PIN 6"就可以接其它数字口。