An infrared proximity sensor works by shining infrared (IR) light out and detecting the intensity of light that’s reflected. If something relatively reflective is quite close to it, the sensor will see a strong reflection, and as that thing gets farther away, the intensity will fall off. The effective range for the devices in the course kit is maybe 2cm–20cm (1”–8”), depending on the ambient light.

The circuit

IR proximity sensor schematic.

The type of sensor we’ve included in the kit simply packages two components right next to each other: an infrared-emitting LED, and an infrared-sensing photocell. Looking at the right side of the schematic, you can see that you’re always keeping the IR emitter powered, using a “ballast resistor” to limit the current that flows through it.

On the left side of the circuit, we build a voltage divider which includes a potentiometer in it. This is so that the total resistance of that leg of the circuit can be adjusted to account for different ambient lighting conditions; you may want to wire up the circuit, hold something reflective at medium range, and then turn the potentiometer until the analogRead() value is reasonable. (Similarly, electronics sometimes have little potentiometers buried in them that probably only ever need to be adjusted once, at the factory, to get things right; these are called “trimpots” for short.)

Arduino code to read an analog value and print via the serial monitor

This is generic code for doing an analog read of an input pin and reporting the results to the Serial Monitor.


int photocell = A0; // shortcut to refer to the photocell pin later

void setup() {
  pinMode(photocell, INPUT); // we will be reading the photocell pin
  Serial.begin(9600); // starts serial communication at 9,600 baud (the rate)
}

void loop() {
  int readVal; // initialize a new integer to store the photocell value
  readVal = analogRead(photocell); // do the analog read and store the value
  Serial.println(readVal); // push the most recent value to the computer
  delay(50); // slow the loop down a bit before it repeats
}