Hi, my program behaves very weird. If I run the code below, the variable elapsedMillis changes its value even though it is not involved in any operation.
I spent the last hours cutting away everything that has no effect on this bug and ended up with the code below. Now if I even delete a Serial.print line, the bug goes away.
In this state "elapsedMillis" is just counting up. If I ad some other unrelated code its value occasionally jumps, too. I'm totally lost with this one. ![]()
This is what the serial monitor looks like:
timerIsOn: 0
cmd: 0
currentMillis: 1073
startMillis: 0
elapsedMillis: 0
----------------------------------
timerIsOn: 0
cmd: 1
currentMillis: 1077
startMillis: 0
elapsedMillis: 0
----------------------------------
timerIsOn: 0
cmd: 0
currentMillis: 1087
startMillis: 0
elapsedMillis: 1087
----------------------------------
timerIsOn: 0
cmd: 1
currentMillis: 1096
startMillis: 0
elapsedMillis: 1087
----------------------------------
This is the code:
// LCD
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
float ovenTemp[2] = {0.0, 0.0};
void setup() {
Serial.begin(115200);
lcd.init();
lcd.backlight();
}
void loop() {
timer(0);
timer(1);
printTemp(ovenTemp[0], 2);
printTemp(ovenTemp[1], 3);
}
void printTemp(float temp, byte line) {
unsigned long currentMillis = 0;
static unsigned long previousMillis[2] = {0, 0};
char printTemp[6];
static char previousPrintTemp[2][6] = {{""}, {""}};
currentMillis = millis();
if (currentMillis - previousMillis[line] > 1000) {
previousMillis[line] = currentMillis;
if (temp <= -50 || temp >= 400) {
} else {
dtostrf(temp, 5, 1, printTemp);
}
}
}
void timer(byte cmd) {
unsigned long currentMillis = 0;
static unsigned long startMillis = 0;
static unsigned long elapsedMillis = 0;
static bool timerIsOn = false;
currentMillis = millis();
Serial.print("timerIsOn: "); Serial.println(timerIsOn);
Serial.print("cmd: "); Serial.println(cmd);
Serial.print("currentMillis: "); Serial.println(currentMillis);
Serial.print("startMillis: "); Serial.println(startMillis);
Serial.print("elapsedMillis: "); Serial.println(elapsedMillis);
if (timerIsOn) {
Serial.println("if statement ran");
elapsedMillis = currentMillis - startMillis;
}
Serial.println("----------------------------------");
}