Hi friends!
I was practicing with Arduino and doing diferents "experiments" when suddenly I had a question. But, sorry.... I have not been able to find an answer... : Why when I place the "serial.println" inside "if" (see the code (1)), it gives me some values completely diferents that when I place it outside of "if" (2). And what should I do to make them equal in both cases?
Thanks!!
unsigned long time_now;
unsigned long time_old;
long a, counter;
void setup() {
 Serial.begin(115200);
}
void loop() {
 counter++;
 time_now = millis();
 if (time_now - time_old >= 90) {
  a = counter;
  time_old = millis();
  //Serial.println(a); <===(1)
  counter = 0;
 }
 Serial.println(a); <====(2)
}
You do realize when, if (time_now - time_old >= 90) is true, ‘a’ is printed in the 1st if, then counter becomes 0, then ‘a’ is printed in the 2nd if.
The values printed will be ‘some number’ and ‘0’.
Well the second one prints unconditionally every time round the loop and often the variable it is printing will not have changed because it's only ever set inside the if statement's conditional code.
follow your code. The first time though the loop, your if statement is false (it hasn't been 90 msec) so it does not execute. When it hits the println(a), the value of a is zero since all global variables are initialized to zero and you have not assigned anything different.
Once 90 ms has elapsed, your if statement is true which means a is assigned the value of counter which will be some very large number since loop() executes many, many, many times in 90 msec. It will then hold that number and print it out every time through the loop until another 90 ms elapses.