I am an experienced programmer in Fortran, but new to Arduino.
if( ) seems to behave incorrectly. Had problem with a larger code, but boiled it down to make an essential example. Here is the entire example code, followed by the output that appears on the Serial Monitor.
Two things are strange -
-
The value of modk seems to be correctly re-calculated the first time and second time through the loop, but is never recalculated on subsequent passes around the loop. modk is supposed to toggle between 0 and 1 every time through the loop.
-
The action controlled by the if( ) statement (which is only a Serial.print) should only occur when modk=1, but, even though modk becomes zero and is stuck at zero as shown by the printed values each time through the loop (instead of toggling between 0 and 1), the action of the if( ) statement is activated nonetheless. Note that the variable kount (printed out) is increasing by 1 each time through the loop as would be expected.
Any explanation ? Both 1) and 2) seem to make no sense.THE CODE :
int modk = 0;
int kount = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
kount = kount + 1;
modk = 1 - modk; // SHOULD TOGGLE modk BETWEEN 0 AND 1
Serial.print(" modk , kount = ");
Serial.print(modk);
Serial.print(" ");
Serial.println(kount);
if(modk = 1) {
Serial.println(" modk must be 1, but prints as 0");
}
Serial.println(" ");
delay(3000);
}
BELOW IS THE OUTPUT ON THE SERIAL.MONITOR.
NOTE THAT modk IS CORRECTLY CALCULATED FIRST TIME AND SECOND TIME, BUT THEN IS ALWAYS STUCK AT 0 (ACCORDING TO THE PRINT).
NEVERTHELESS, THE if( ) BEHAVES AS IF THE VALUE OF modk IS ALWAYS 1 AND NEVER CHANGES.
modk , kount = 1 1
modk must be 1, but prints as 0
modk , kount = 0 2
modk must be 1, but prints as 0
modk , kount = 0 3
modk must be 1, but prints as 0
modk , kount = 0 4
modk must be 1, but prints as 0
modk , kount = 0 5
modk must be 1, but prints as 0
. . . etc., endlessly with kount incrementing by 1 each time and modk always 0