Hardware Reference
In-Depth Information
// this will not be executed because n is not greater than 10
digitalWrite(redLed, HIGH);
}
if (n < 10) {
// this will not be executed because n is not less than 10
digitalWrite(greenLed, HIGH);
}
if (n == 10) {
// this will be executed because n equals 10
digitalWrite(yellowLed, HIGH);
}
It's important to remember that a single equal sign is used to
assign values to variables and a double equal sign is a com-
parison operator to check if one value is the same as another.
It's very unlikely that you'll ever use the assignment operator
inside an if statement's parentheses. I find that it's an easy
mistake to make. Unfortunately, you will not get an error from
the compiler if you make this mistake, and your sketch won't
behave as expected.
You can have multiple tests in a single if statement. The logical operators to
help you do this are listed in Table 3-2 . There's also a not operator to negate
any result.
Table 3-2. Logical operators
Operator
Meaning
&&
and
||
or
!
not
Here are a few examples to demonstrate how the logical operators work so
that you can test for two conditions at once:
int n = 10;
if ( (n > 8) && (n < 12) ) {
// this will be executed because n is greater than 8 and less
// than 12
digitalWrite(redLed, HIGH);
}
if ( (n > 8) && (n < 10) ) {
// this will not be executed because n is not less
// than 10 even though it is greater than 8. With &&,
// both must be true.
 
Search WWH ::




Custom Search