[英]Code keeps looping even if serial is available
I'm using an external application to sync my RGB peripherals with my WS2812B Strip. 我正在使用外部应用程序将RGB外设与WS2812B Strip同步。 I wanted to make a default color that it could switch to when the application isn't running but after 2 seconds of enabling the strip in the software, it goes back to the default color I set (255,255,255).
我想设置一种默认颜色,可以在应用程序不运行时切换为默认颜色,但是在启用软件中的色带2秒钟后,它又恢复为我设置的默认颜色(255,255,255)。
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUMPIXELS 30
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +
NEO_KHZ800);
void setup() {
pixels.begin();
Serial.begin(19200, SERIAL_8E1);
}
void loop() {
for (int w = 0; w < NUMPIXELS; w++) {
pixels.setPixelColor(w, 255, 255, 255);
}
pixels.show();
int w = 0;
if (Serial.available()) {
int n = 0;
for (int n = 0; n < 3; n++) {
byte rgb[3];
Serial.readBytes(rgb, 3);
uint32_t r = int(rgb[0]);
uint32_t g = int(rgb[1]);
uint32_t b = int(rgb[2]);
for (int i = 0; i < NUMPIXELS; i++) {
pixels.setPixelColor(i, r, g, b);
}
pixels.show();
}
}
}
The function Serial.available()
does something else than what you expect: 函数
Serial.available()
执行的功能Serial.available()
您的预期:
You expect it to return if there is a communication partner available. 如果有通讯伙伴可用,您希望它返回。 Instead it checks if there are bytes to read available:
相反,它检查是否有可用的字节读取:
Get the number of bytes (characters) available for reading from the serial port.
获取可用于从串行端口读取的字节数(字符)。 (Source: https://www.arduino.cc/en/Serial/Available )
(来源: https : //www.arduino.cc/en/Serial/Available )
This means: Your Arduino has run out of bytes to read, because it empties the pipeline too fast. 这意味着:您的Arduino用尽了很多字节来读取,因为它清空管道的速度太快了。 So, as there are no more bytes to read, it will just make the leds show white.
因此,由于不再需要读取更多字节,因此只会使LED显示白色。
Sidenote: The if condition should be changed to reflect this (see post on Arduino website): 旁注:应更改if条件以反映此情况(请参阅Arduino网站上的文章):
if (Serial.available() > 0) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.