I am trying to write a test code on Arduino with a LED Matrix I have built. I wrote a couple of functions for animating graphics on the LED Matrix and wanted to change the animation at different integer 'parseInt' through Serial monitor. However, I am able to get into either one of the 'states' but once I am in one of the states, I cannot transition to another when I send a different integer that supposedly activate its corresponding state.
Does anyone know what I am doing wrong here? The code is as shown below:
int state = 0;
void loop() {
while (Serial.available() > 0) {
int mm = Serial.parseInt();
if (mm == 1) {
state = 1;
while (state == 1) {
animation1();
}
} else if (mm == 2) {
state = 2;
while (state == 2) {
animation2();
Serial.println(state);
}} else if (mm == 3) {
state=3;
while (state ==3) {
animation3();
}
}
}
}
I tried creating boolean variables, and tried also printing out the state the pixels is animating but it seems like once it enters one of the state it won't even read the new character sent via the serial monitor.
just a note that solely putting the animation function inside if statement didn't work as it only displayed the 1st frame of the animation and not continuously... that's why I used the while loop
You should not use while loop , it will cause an infinite loop there. So it will just stuck there indefinetely.
Try this
void loop() {
while (Serial.available() > 0)
{
int mm = Serial.parseInt();
while(Serial.available() > 0)
{
Serial.read(); // This code to flush the new line character "/n"
}
while(Serial.available() == 0)
{
if (mm == 1)
{
animation1();
}
else if (mm == 2)
{
animation2();
}
else if (mm == 3)
{
animation3();
}
}
}
}
}
Edit : So we can add a while loop to check if there is no other output yet then just loop again and again. If there are new output stop the loop and print the new animation.
2nd Edit : This is a bug fix for the new line character that might intefer with the loop
3rd Edit : Cleanup code