Comparative and Logical Operators

Conditional statements like the for loop and if statement discussed in this chapter use comparison and logical operators to test for conditions. Comparative operators are used to compare the left side of an expression against the right side to produce a value of true or false. With this piece of information, the Arduino can use it to make decisions depending on the type of control structure being used. So if you wanted to test whether or not a variable held a particular value, you might use an expression like the following:

myValue == 5

Here we use the == comparative operator to test if the variable or value on the left of the operator is equal to the variable or value on the right. In this case, the expression would return as true if myValue contained the value 5, and false if it did not. You should note that we use the phrase “is equal to” instead of “equals”. This helps us to differentiate the comparison operator (==) from the assignment operator (=), with the former referred to as “is equal to” and the later “equals”.

Table 4-1 lists other comparative operators that we will discuss in greater depth and provide examples for in this chapter and beyond.

images

Comparative operators work great if needing to compare two values against each other, but you might need to make some more complex logical comparisons. In this way, you could use a logical operator, for example, to make two separate comparisons, and only do something if both comparisons are true. Consider the following example expression:

myValue >= 10 && myValue <= 20

This expression uses the logical and (&&) operator, returning true if and only if the conditional statements on both the left and the right are true. In this case, this statement will be true if myValue contains a value greater than or equal to 10 and less than or equal to 20. This creates a range of numbers between 10 and 20 that could be true.

Conversely, the logical or (||) operator will return a value of true if either of the conditional statements on the left or right is true. Take this following example:

myValue < 10 || myValue > 20

This line would only return true if myValue contained a value that was less than 10 or greater than 20, excluding the values from 10 through 20.

The final logical operator is the not (!) operator. This one is a little different from the others in that it works on only one operand and returns true only if the expression is false. Take the following example:

!myValue

This line will return true only if myValue is false or contains the numerical value of 0.

Comparative and logical operators are going to play a crucial part in the Arduino decision-making process. Table 4-2 provides a quick reference of the logical operators to refer back to.

images

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.80.122