digitalWrite(LED,!LED);

good day guys :slight_smile:

digitalWrite(LED,!LED);

is this valid? for example… i assigned LED a value… then i want to NOT the value of LED in my next statement… is that valid? will my arduino execute the code? If not, how can i NOT the LED? thanks…

You are on the right track but you need another variable. The first parameter to digitalWrite is the pin number, you don’t want to invert that. Also the second parameter is declared as an unsigned 8 bit value, not as a Boolean so I prefer to use the C ternary operator as follows:

int ledPin = 13
int ledState = LOW;

ledState = ledState ? LOW: HIGH; // C ternary operation to flip the value between LOW and HIGH
digitalWrite(ledPin, ledState);

or, if you want to do it in a single expression:

digitalWrite(ledPin, ledState = ledState ? LOW : HIGH);

The ternary operator may look odd at first but its useful and expressive once you get familiar with it.

thanks mem! im going to try it… i’l give you feedback once im done! again, many thanks my friend… :wink:

im sorry but i have another problem…

what if the code is like this…

digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);

.
.
.
.

then i want to invert the values of LED1 and LED2… how will i do that? im sorry… i only have a little experience in programming… :-/

You could do this:
digitalWrite(led1Pin, led1State = led1State ? LOW : HIGH));
digitalWrite(led2Pin, led2State = led2State ? LOW : HIGH);

or have a function that inverted the value:

uint8_t invert( uint8_t value){
// returns LOW if the given value is HIGH, else HIGH if the given value is LOW
if( value == LOW)
return HIGH;
else
return LOW;
}

led1State = invert(led1State);
digitalWrite(led1Pin, led1State);

Note that the invert function does that same as same as:
value = value ? LOW : HIGH;

Much simpler than the examples above, if you just want to toggle the output of a single pin you can do:

digitalWrite(ledPin, !digitalRead(ledPin));

thanks for the help