好的,我对这段代码有一个令人困惑的问题。计数器pushCounterz
(以z命名只排除冲突变量)将以正确的计数器(1或0或其中任何一个)开始,按下按钮时会发生以下几种情况之一:
#include <FastLED.h>
#define AnalogIn A0
#define SwIn 2
#define LED_Out 12
#define NUM_LEDS 100
int pushCounterz = 0;
int buttonState;
int lastButtonState; // the previous reading from the input pin
int ledPin = 13;
int ledState = HIGH;
CRGB leds[NUM_LEDS];
void setup() {
// put your setup code here, to run once:
FastLED.addLeds<WS2812, LED_Out, GRB>(leds, NUM_LEDS);
//pinMode(SwIn, INPUT);
pinMode(LED_Out, OUTPUT);
pinMode(ledPin, OUTPUT);
//Turn Off strip
for (int i = 0; i <= NUM_LEDS; i++) {
leds[i] = CRGB ( 255, 0, 0 );
FastLED.show();
}
digitalWrite(ledPin, ledState);
Serial.begin(115200);
Serial.println(pushCounterz);
lastButtonState = digitalRead(SwIn); // Set the button state to the startup state
}
void loop() {
buttonState = digitalRead(SwIn);
if (buttonState == LOW && buttonState != lastButtonState) {
ledState = !ledState;
}
if (buttonState == LOW && buttonState != lastButtonState) {
if (pushCounterz > 3) {
Serial.println("Reset to 0: ");
pushCounterz = 0;
} else {
pushCounterz = pushCounterz + 1;
Serial.println("Incerment");
}
Serial.println(pushCounterz);
switch (pushCounterz) {
case 0:
for (int i = 0; i <= NUM_LEDS; i++) {
leds[i] = CRGB (255, 0, 0);
}
break;
case 1:
for (int i = 0; i <= NUM_LEDS; i++) {
leds[i] = CRGB ( 0, 255, 0);
}
break;
case 2:
for (int i = 0; i <= NUM_LEDS; i++) {
leds[i] = CRGB ( 0, 0, 255);
}
break;
case 3:
// theaterChaseRainbow(1,50);
break;
default:
for (int i = 0; i <= NUM_LEDS; i++) {
leds[i] = CRGB ( 0, 0, 0);
}
break;
}
}
FastLED.show();
digitalWrite(ledPin, ledState);
lastButtonState = buttonState;
}
但是,如果我禁用开关代码块,一切都可以正常运行。我怀疑这是FastLED库中的一个错误,但是我想在这里问一下,因为我对Arduino编程很不错。
编辑:上面的代码修复了按钮的一个问题。我已将电路更改为高电平并降低电平,但是没有更改代码。然而,状态仍然不一致,有时工作,有时在1和-255之间翻转(更多 - 后者)。变更摘要:
void setup() {
...
lastButtonState = digitalRead(SwIn); // Set the button state to the startup state
}
*/
buttonState = digitalRead(SwIn);
if (buttonState == LOW && buttonState != lastButtonState) {
ledState = !ledState;
}
if (buttonState == LOW && buttonState != lastButtonState) {
编辑:串行输出以显示上述编辑后的当前疯狂(带注释):
0 <- initial startup correct
Incerment <- button push
1 <- correct increment
Incerment <- 2nd button push
-255 <- 1 + 1 does NOT equal -255
Incerment <- 3rd button push
1 <- ??? Assuming -255 +1 = 1?
Incerment
-255
答案 0 :(得分:0)
使用
for (int i = 0; i <= NUM_LEDS; i++)
您正在使用索引100,它是数组的第101个元素。
这是未定义的行为,在您的情况下会导致pushCounterz
出现问题。
使用for
更改leds
运算符,修复所有遍历<=
的{{1}}循环。
<