This is one of the most bizarre errors I've ever experienced. I am using two LEDs as indicator lights for a project I am working on, a red and a green. One of the status codes I want to implement is for it to alternately flash the green LED and the red LED four times total. When I tested my implementation, it flashed the green LED first once, then the red LED three times. I wanted to make sure the loop was iterating properly, so I added Serial.println()'s to test that. For some reason this made the code produce the expected output. *iter isn't changed or modified in any way, but if I comment out that println the incorrect behavior resumes. Below is all of the relevant code, as tested in isolation to confirm it wasn't something else causing the problem. If anyone can tell me what is going on I would appreciate it, I am so confused right now.
// Function prototype probably unnecessary but being thorough
void redGreenLED (int *mode, int *iter, unsigned long *timer);
// Human-friendly pin names, using analogs as digital because every
// single pin I can use is being used for this project
const int pinG = A2;
const int pinR = A3;
// Global variables for LED control
int rgMode = 0;
unsigned long rgTimer = 0;
int rgIter = 0;
void setup() {
Serial.begin(9600);
// assign I/O
pinMode(pinG, OUTPUT);
pinMode(pinR, OUTPUT);
// delay for convenience
delay(1500);
// flash red and green alternately 4 times
rgMode = 1;
}
void loop() {
redGreenLED(&rgMode, &rgIter, &rgTimer);
}
void redGreenLED (int *mode, int *iter, unsigned long *timer) {
if (*mode == 1) {
// Alternately flash red and green for 100 ms four times
if (*iter < 8) {
if (!(*iter % 2) && !(*iter % 4) && (millis() - *timer) > 75) {
Serial.println(*iter); // Why does this being included make a difference???
digitalWrite(pinG, HIGH);
*timer = millis();
*iter += 1;
} else if (!(*iter % 2) && (millis() - *timer) > 75) {
digitalWrite(pinR, HIGH);
*timer = millis();
*iter += 1;
} else if ((*iter % 2) && (millis() - *timer) > 100) {
digitalWrite(pinR, LOW);
digitalWrite(pinG, LOW);
*timer = millis();
*iter += 1;
}
} else {
*iter = 0;
*mode = 0;
}
}
}