Hi
In "Planning and Implementing an Arduino Program" robin2 uses this code
ledAstate = ! ledAstate;
i tried a simple sketch implementing this instead of my usual dumb way.
It works but not as expected, if i put it at the beginning of the if it works, if i put it at the end of the if it became erratic and remains in a 1 or 0 for several cycles seemingly random.
unsigned long x;
bool ledstate = 0;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
}
void loop() {
if (millis() > x + 1000L)
{
ledstate = !ledstate;
if (ledstate == 0)
{
digitalWrite(13, HIGH);
Serial.println("on");
}
if (ledstate == 1)
{
digitalWrite(13, LOW);
Serial.println("off");
}
x = millis();
}
//comment the other at the beginning before uncommenting this
//ledstate = !ledstate;
}
the resulting sequence with the =! at the end is this
on
on
on
on
off
on
on
on
off
on
on
on
on
off
on
off
on
on
on
off
off
off
on
off
on
off
off
on
There is no =! operator. There is an assignment operator (=) and a not operator (!).
The ! operator changes true to false or false to true. Since ledstate is either 0 or 1, and those are the same values as true or false, it is simply changing HIGH to LOW or LOW to HIGH (also assigned the values 0 and 1).
Since the ONLY values that ledstate can have are 0 or 1, if the value is not 0 it MUST be 1, so the second if is pointless. It should be an else statement.
Why are you not writing ledstate to the led?
As to your question, in one case the toggle happens on every pass through loop(). In the other, it happens inside the if enough time has elapsed block.
The "!" is a NOT operator. So if used as "!=" it means not equal to but it can also be used to invert. If you have a boolean value that is either true or false, and you put "!" in front of it, it's going to invert it to the opposite.
Example:
bool ledstate = 0; // ledstate is false
ledstate = !ledstate; // ledstate is inverted "not ledstate".... ledstate = 1 (true)
if (ledstate == 0) // if ledstate is false, execute code
remains in a 1 or 0 for several cycles seemingly random.
Exactly so.
In the case where ledSate = !ledState is at the end of the loop, it is outside of the conditional test which occurs every second, and the variable ledState is changing every time through the loop. This changing of state happens many, many times per second and it is a matter of chance in what state it is in when the conditional test happens to come around each second.
In the case where ledSate = !ledState is at the end of the loop, it is outside of the conditional test which occurs every second, and the variable ledState is changing every time through the loop. This changing of state happens many, many times per second and it is a matter of chance in what state it is in when the conditional test happens to come around each second.
Mmmmh i must be very tired, i was really sure that the second =! case was inside the "if (millis() > x + 1000L)"
I'm really sorry!