When building my little TailLight project I randomly got in to an issue where a variable who gets it's value by digitalRead just changes its value in the middle of the code without assigning the variable a new value.
After some troubleshooting I find where the value get changed in the code.
I do some Serial.println(leftState) two times in a row, first it prints 0 then the next time it prints 50
Why?
You will find the problem in the code below, in the "checkWarning" function.
Super confused :o
#include <FastLED.h>
#define NUM_LEDS 8
#define DATA_PIN 7
#define LEFT_PIN 6
#define RIGHT_PIN 3
#define WARN_PIN 5
#define BRAKE_PIN 4
int leftState = 0;
int rightState = 0;
int warnState = 0;
int brakeState = 0;
bool blinkOn = true;
CRGB leds[NUM_LEDS];
void setup() {
Serial.begin(9600);
//Init buttonpins
pinMode(LEFT_PIN, INPUT);
pinMode(RIGHT_PIN, INPUT);
pinMode(WARN_PIN, INPUT);
pinMode(BRAKE_PIN, INPUT);
//Init LEDs
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}
void loop() {
checkPressedButtons();
checkBrakes();
checkBlinkTime();
if (checkWarning() != true) {checkBlinkers();}
FastLED.show();
}
//Check for pressed buttons
void checkPressedButtons() {
leftState = digitalRead(LEFT_PIN);
rightState = digitalRead(RIGHT_PIN);
warnState = digitalRead(WARN_PIN);
brakeState = digitalRead(BRAKE_PIN);
}
//Check if brakes are applied
void checkBrakes() {
if (brakeState == LOW)
for (int i = 0; i <= NUM_LEDS; i++) {leds[i] = CRGB(50,0,0);}
else
for (int i = 0; i <= NUM_LEDS; i++) {leds[i] = CRGB(255,0,0);}
}
//Check if blinkers are applied
void checkBlinkers() {
if (blinkOn == true) {
if (leftState == HIGH) {
for (int i = 0; i <= 2; i++) {leds[i] = CRGB::Orange;}
} else if (rightState == HIGH) {
for (int i = 5; i <= NUM_LEDS; i++) {leds[i] = CRGB::Orange;}
}
}
}
//Check if warninglights are applied
bool checkWarning() {
Serial.println(leftState); //Here value is 0 if button not pressed and 1 if button is pressed.
Serial.println(leftState); //Here value is 55 neither if the buttons is pressed or not. Why?
if (warnState == HIGH) {
if (blinkOn == true) {
for (int i = 0; i <= 2; i++) {
leds[i] = CRGB::Orange;
}
for (int i = 5; i <= NUM_LEDS; i++) {
leds[i] = CRGB::Orange;
}
}
return true;
}
return false;
}
void checkBlinkTime() {
//Not yet finished
}
I don't think there is any problem with the wiring because it worked earlier.
But I will include a picture of a fritzing just because I can and want an answer on this problem.
