Datasheet

Navigating with Infrared Headlights • Chapter 7
Robotics with the BOE Shield-Bot 227
delay(100); // 0.1 second delay
}
// IR Object Detection Function
int irDetect(int irLedPin, int irReceiverPin, long frequency)
{
tone(irLedPin, frequency, 8); // IRLED 38 kHz for at least 1 ms
delay(1); // Wait 1 ms
int ir = digitalRead(irReceiverPin); // IR receiver -> ir variable
delay(1); // Down time before recheck
return ir; // Return 1 no detect, 0 detect
}
Inside TestBothIrAndIndicators
After the two calls to the irDetect function, irLeft and irRight each store a 1 if an object
is not detected, or 0 if an object is detected. The sketch could have used an
if…else
statement to turn the indicator lights on/off depending on the value of
irLeft and irRight.
But, there are other ways!
This approach uses the values of
irLeft and irRight directly. There’s only one catch:
when (for example)
irLeft stores 0, we want its red indicator LED to turn on, and if it
stores 1, we want its LED to turn off. Since 1 makes the indicator LED turn on and 0 turns it
off, using
digitalWrite(8, irLeft) would give us the opposite of what we want. So, the
sketch uses the not operator (
!) to invert the value that irLeft stores. Now,
digitalWrite(8, !irLeft)
inverts the value of IrLeft so that when it stores a zero, the
LED turns on, and when it stores 1, the LED turns off. The same technique is applied for the
right IR detector and indicator LED.
The Not (!) Operator inverts all the binary values in a variable. There’s more going on
with digitalWrite(8, !irLeft) here than meets the eye. You’re probably used to passing
the digitalWrite function’s value parameter either HIGH (constant for 1) to turn the light on,
or LOW (constant for 0) to turn the light off. When you use variables, the digitalWrite function
uses the variable’s rightmost binary digit: 1 to turn the light on, or 0 to turn the light off. So,
when irLeft is 0 (object detected) !irLeft changes its binary value 00000000 to 11111111. It
has a 1 in the rightmost digit, so the light turns on. When irLeft is 1, it’s really binary 00000001.
The
!irLeft statement results in binary 11111110. Rightmost digit is 0, so the light turns off.
Your Turn Remote Testing and Range Testing
With the indicator LEDs working, you can now unplug the BOE Shield-Bot from its
programming cable and test detection with a variety of objects. Since certain objects reflect
infrared better than others, the IR object detectors will be able to see some objects further
away, and others only when very close.