Adventures in Science: Arduino Logic Operators

Building on our last Arduino programming episode, we look at creating compound conditional statements using logic operators.

On this week's "Adventures in Science," we look at creating compound conditional statements. But in order to do that, we first cover the basics of Boolean logic (or Boolean algebra).

There are three main operators in Boolean algebra: NOT, AND, OR. From these, we can make any number of logic statements, but for now, we will only cover these three and exclusive OR. Boolean algebra follows its own set of rules, but the most important one to remember is that variables can only have one of two values: true or false. From there, we can show how the different operators work.

The first, and probably easiest, is the NOT or negation operator. It simply returns the opposite value of the variable it modifies (P, in this case).

P !P
False True
True False

The second is the AND operator, which is more formally known as logical conjunction. With it, both variables (P and Q) must be true for the result to be true.

P Q P && Q
False False False
False True False
True False False
True True True

Next, we have the OR operator (logical disjunction). We know this in English as "inclusive or," which means that either P, Q or both can be true for the result to be true.

P Q P || Q
False False False
False True True
True False True
True True True

Finally, we have exclusive OR (exclusive disjunction), where only one of P or Q can be true for the result to be true. If both are true, the result is false. Exclusive OR is not considered a fundamental logic operator, as you can construct the operation from the other three:

P ⊕ Q = (P || Q) && !(P && Q)

One possible operator for exclusive OR is a plus enclosed in a circle, ⊕. There's no Boolean operator for exclusive OR C, but it's important enough in programming and electronics that I felt the need to introduce it.

P Q P ⊕ Q
False False False
False True True
True False True
True True False

Using logical operators, we can create compound conditional statements that make doing things like detecting a button push edge much easier:

const int btn_pin = 7;
const int led_pin = 13;

int btn_prev = HIGH;
int btn_state;

void setup() {
  pinMode(btn_pin, INPUT_PULLUP);
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
}

void loop() {
  btn_state = digitalRead(btn_pin);
  if ( (btn_state == LOW) && (btn_prev == HIGH) ) {
    digitalWrite(led_pin, HIGH);
    delay(500);
    digitalWrite(led_pin, LOW);
  }
  btn_prev = btn_state;
}

Are there any other slick uses for Boolean operators and compound conditional statements that you can offer or would want a new programmer to know? Please share your ideas in the comments below.