First tests using the ESP32.
Simple test code below.
If I place a digitalRead(GPIO17); -- or a digitalWrite
before the if (x >= 2000L) the code works
If I don't do the digital read or write,
then the (x >= 2000L) always evaluates as true
and toggles GPIO4 very quickly
Any idea what is happening?
Thanks
#define GPIO4 4
#define GPIO2 2
#define GPIO17 17
#define NOP __asm__ __volatile__("nop\n\t")
void setup() {
Serial.begin(9600);
pinMode(GPIO4, OUTPUT);
pinMode(GPIO2, OUTPUT);
pinMode(GPIO17, INPUT);
}
void loop() {
long x = 0L;
char VAL = 0;
Serial.println("\n\rReady>\n\r");
while (1) {
x++;
// digitalWrite(GPIO2,VAL);
digitalRead(GPIO17); // if add this line process if (x >=...) properly
if (x >= 2000L) // for some reason acts as always true-if no digitalRead or digitalWrite before it
{
x = 0L;
VAL = !VAL;
digitalWrite(GPIO4, VAL);
} // end of if (x)
} // end of while
} // end of loop()
What is connected to this pin so that you can conclude that it is working (or not) ?
Adding a digitalRead() or digitalWrite() or making a variable volatile will add a short pause in your while() loop. 2000 loop iterations will happen very quickly so you'll need a scope or logic analyser to see anything.
I had a scope on the GPIO output pin so I could see the toggling of the output.
The difference between 2000 and 4000 is very easy to see (it halves the image on the scope). I had tried numbers like 4000000L and had the same problem.
I've found, without the volatile, the optimization allows very quick processing (using the value from the accumulator -a compiler optimization, not a regular memory fetch)
If you do something which is undefined, the compiler can simply and silently generate rubbish. Here is a recent example: Odd code behaviour, just FYA
As has already been pointed out, this is odd looking in that it is a logical NOT operation on a signed number. I could guess this may cause odd behaviour.