When i was testing out a program I found a strange behavior of esp8266
It seems to get out of a while loop even when there's no option of getting out on code
I don't know if these are related but here's the code (the program is just two different visual patterns of leds toggled by a button)
#define led1 D0
#define led2 D1
#define led3 D2
#define led4 D3
#define button D7
unsigned long pressedButton;
bool change = 0;
unsigned long previousTime;
unsigned int difference;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(button, INPUT_PULLUP);
}
void loop(){
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW); //when the while loop change, this should delete interference
digitalWrite(led4, LOW);
previousTime = millis();
while (!change){ //default visual pattern of leds
difference = millis()-previousTime;
if (!digitalRead(led1) && difference>=200){
digitalWrite(led1, HIGH);
}
if (!digitalRead(led2) && difference>=400){
digitalWrite(led2, HIGH);
}
if (!digitalRead(led3) && difference>=600){
digitalWrite(led3, HIGH);
}
if (!digitalRead(led4) && difference>=800){ //after here, all the leds should be HIGH
digitalWrite(led4, HIGH);
}
if (digitalRead(led4) && difference>=1000){
digitalWrite(led4, LOW);
}
if (digitalRead(led3) && difference>=1200){
digitalWrite(led3, LOW);
}
if (digitalRead(led2) && difference>=1400){
digitalWrite(led2, LOW);
}
if (digitalRead(led1) && difference>=1600){ //after here, all the leds should be LOW
digitalWrite(led1, LOW);
previousTime = millis();
}
if (!digitalRead(button) && millis()-pressedButton>200){ //check if button was pressed to break while loop
pressedButton = millis();
break;
}
}
while (change){ //alternative of visual pattern of leds
difference = millis()-previousTime;
if (!digitalRead(led1) && difference>=200){
digitalWrite(led1, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
}
if (digitalRead(led1) && difference>=400){
digitalWrite(led1, LOW);
digitalWrite(led4, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
previousTime = millis();
}
//if (!digitalRead(button) && millis()-pressedButton>=200){ //check if button was pressed to break while loop
// pressedButton = millis();
// break;
//}
}
change = !change; //after a break in one of the while loops, this will make the program go to the other while loop
}
Is there something wrong with the code? Here is a link of a video of the behavior for more details https://drive.google.com/file/d/1822MHNGQn-A2-HGHhRXz_8xydz-wM4Ha/view?usp=sharing