Lessons · Lesson S1 · Sensors · 20 min
Light and infrared sensors
Meet your first digital sensor, an infrared break-beam pair that tells your ESP32 whether something is blocking an invisible line. About 20 minutes, with a beam you can break on screen.
A sensor that answers yes or no
In lesson K2 you read a button: the pin was high or low, and your code reacted. A digital sensor is the same thing with the finger taken away. It has only two possible answers, and you read them with digitalRead().
Today’s sensor answers one question: “is something blocking the line between these two parts?” It is an infrared break-beam pair, the sensor behind mission 01, the intrusion alarm. It makes a good first sensor because everything from K2 carries over: the same INPUT_PULLUP, the same “LOW means something is happening”, the same if / else.
Why choose a break-beam rather than a motion sensor? Adafruit’s description gives two reasons: a break-beam is faster than a PIR motion sensor and lets you decide exactly where the detection happens, and it costs less than a sonar module. The catch is that it needs two parts, one on each side of the area you watch [1].
Two halves, one invisible line
The pair has two separate parts [1][2]:
- The emitter sends out a beam of infrared (IR) light that people cannot see. It is an infrared LED [1], not a laser.
- The receiver sits across from it and reacts to that same light. When something that is not transparent to infrared passes between the two, the beam is “broken” and the receiver reports it [1].
Infrared is light with a slightly longer wavelength than the light we see, which is why our eyes miss it [3].
Wires. The emitter has two (red and black). The receiver has three: red for power, black for ground, and a white or yellow one for the signal, called OUT [2]. No wire runs from one half to the other: the signal crosses the gap as light, so the two halves do not even need the same power supply [2].
The 5 mm pair we use (Adafruit’s product page) [1]:
| What | Value |
|---|---|
| Sensing distance | about 50 cm (Adafruit); 5 V gives the best range, 3.3 V works with less (no figure given) |
| Supply | 3.3 V to 5.5 V |
| Emitter current | about 10 mA at 3.3 V, 20 mA at 5 V |
| Response time | under 2 ms |
| Beam angle (each LED) | 10° |
In mission 01 the two halves sit 15 to 20 cm apart. That should leave a margin at 3.3 V. Test your own pair rather than trusting a number.
Aim it. The LEDs have a narrow angle [1], so face the two halves at each other and fix them so they cannot wobble.
See the invisible. SparkFun notes that most phone cameras can pick up infrared and show an IR LED as a faint glow [3]. Point your camera at the powered emitter: if you see a glow, it is alive. If you see nothing, that is a clue, not proof, because your camera may not show it.
Why not an LDR? An LDR (the light sensor you will use in lesson K3, coming up later) is good at visible light, but Adafruit explains that photocells are not good at infrared [4]. It would be a poor choice for this beam.
What the receiver tells your board
The OUT wire is open collector [1][2]. In plain words: the receiver can pull the wire down to ground, but it cannot push it up. Left alone, the wire would float, just like the button pin in K2. So the wire needs a pull-up resistor to hold it high [1][2].
The ESP32 has one inside: about 45 kΩ, switched on with INPUT_PULLUP [5]. Adafruit adds that if your board has no built-in pull-up, a 10 kΩ resistor between the OUT wire and the red wire does the job [1]. On the ESP32 you do not need it. If you ever add an external pull-up, connect it to 3V3, never to a 5 V wire (see the wiring note below). That is exactly the trick from K2, with a sensor in place of the button:
pinMode(32, INPUT_PULLUP);
What your code reads, then [2]:
| Beam | digitalRead(32) |
|---|---|
| Clear (the receiver sees the emitter) | HIGH (1) |
| Broken (something in the way) | LOW (0) |
Same rule as the button: the event is LOW.
Wiring. The receiver’s red wire to 3V3, black to GND, OUT to GPIO 32. Everything stays at 3.3 V, which matters because the ESP32 runs on 3.3 V logic and its pins are not 5 V safe unless stated otherwise [7]. Adafruit allows 3.3 V or 5 V for the receiver supply [2]; 3V3 keeps things simple, at the cost of some range [1].
GPIO 32 is a good pick. GPIO 34 to 39 have no internal pull-up, so they could not do this job [6], and GPIO 32 is not among them.
The emitter takes 3.3 V to 5.5 V [1]. For this lesson, put it on the same 3V3 and GND rails: it draws about 10 mA at 3.3 V [1]. In mission 01 it has its own battery pack because it sits on the door, away from the board.
Break the beam
Time to see it. Move the object into the beam and watch what the pin does. Then switch on “sunlight” and see how a receiver can be fooled.
Swipe the drawing sideways to see all of it.
Drag the hand down into the beam, or use the button.
The whole sketch
Upload this, with the circuit built:
// Tinker Mission, lesson S1: infrared break-beam receiver -> LED + active buzzer
// Wiring:
// IR receiver: red wire to 3V3, black wire to GND, white or yellow wire (OUT) to GPIO 32
// IR emitter: red wire to 3V3, black wire to GND, facing the receiver (in mission 01 it has its own power)
// LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
// Active buzzer: + leg to GPIO 25, other leg to GND (3-pin module: VCC to 3V3, GND to GND, I/O to GPIO 25)
const int BEAM_PIN = 32;
const int LED_PIN = 26;
const int BUZZER_PIN = 25;
int lastState = HIGH; // what the pin said on the previous pass (HIGH = beam clear)
int breakCount = 0; // how many times the beam has been broken since power-up
void setup() {
Serial.begin(115200);
pinMode(BEAM_PIN, INPUT_PULLUP); // the receiver can only pull the wire down: the pull-up holds it high
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
int state = digitalRead(BEAM_PIN); // HIGH = beam clear, LOW = beam broken
if (state == LOW) {
// broken
digitalWrite(LED_PIN, HIGH);
digitalWrite(BUZZER_PIN, HIGH);
if (lastState == HIGH) { // it was clear a moment ago, so this is a NEW break
breakCount = breakCount + 1;
Serial.print("Beam broken. Count: ");
Serial.println(breakCount);
}
} else {
// clear
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
if (lastState == LOW) { // it was broken a moment ago: the beam is back
Serial.println("Beam clear.");
}
}
lastState = state; // remember it for the next pass
delay(10); // 100 checks per second is plenty
}
Download the sketch folder (.zip)
The sketch keeps one extra memory, lastState: what the pin said on the previous pass. Without it, the code would print “Beam broken” a hundred times a second for as long as your hand stays in the beam. With it, the code can tell “still broken” from “just broken”. It checks the state change: Adafruit’s own example for this sensor uses the same idea [2].
Open the Serial Monitor at 115200 baud. Wave your hand across the beam once: you should see one Beam broken. Count: 1 line, and Beam clear. when you pull the hand away. The LED and the buzzer follow the beam.
Troubleshooting.
- LED and buzzer stay on, the monitor says broken, and nothing is in the way: the halves are not facing each other, the emitter is off, or the gap is too long. Move them closer, check the emitter’s two wires, and try the phone camera test from screen 2.
- Nothing ever happens, even with your hand in the way: check the OUT wire on GPIO 32 and that
setup()saysINPUT_PULLUP. An object that is transparent to infrared will not break the beam, so test with your hand or a book first [1]. - It is the other way round (LED on when the path is clear): another make of module may behave in reverse. Let the Serial Monitor tell you what yours does. If it is reversed, add the line
state = !state;just afterint state = digitalRead(BEAM_PIN);. The!turns 1 into 0 and 0 into 1, so the rest of the sketch sees the opposite. - The count jumps by itself, or a break is missed: something is shaking the parts, or a bright infrared source is nearby. See the next screen.
What the receiver “sees”
The receiver does not know which light is yours. It reacts to infrared, and infrared comes from more than your emitter. SparkFun puts it plainly: the sun, light bulbs and anything hot are very bright in the infrared [3].
That is why remote controls do not simply send a steady light. They switch the infrared on and off 38,000 times a second, so the receiver in a television can pick the signal out of all the other infrared around [3]. Adafruit describes no such trick for this simple pair. Instead it warns that daylight contains infrared, so the pair works best in a dim room, where nearly all the infrared reaching the receiver comes from your own emitter [2]. Without that trick, extra infrared at the receiver most likely looks like “beam present”, so bright light can make the alarm miss breaks or behave erratically (typical, to confirm on the bench):
- Keep the receiver out of direct sunlight, and away from a bare bulb pointing straight at it.
- If the alarm has to work in a bright room, Adafruit suggests another kind of sensor, such as a distance sensor or a PIR motion sensor [2].
- If the alarm misses breaks or behaves oddly, think “bright light” before you think “ghost”.
- Test: with the pair running and the Serial Monitor open, turn the receiver towards a window or a lamp and watch the count. What you see depends on your pair, your room and the hour: that is the point of testing.
Two more usual suspects for false alarms: the halves are loose and shift when a door shuts, or the supply is weak. At 3.3 V the range is shorter than at 5 V [1], so a tired battery can make the beam fail at a distance that used to work.
Try your own changes
Change one thing, upload, observe.
- Longer gap. Move the halves apart a few centimetres at a time. At what distance does the count start misbehaving?
- Thin objects. Try a sheet of paper, a clear plastic cup, your hand. Which ones break the beam?
- Count to three. Change the sketch so the buzzer only sounds once the beam has been broken three times.
Check yourself
Three short questions. Nothing is saved, take your time.
The receiver's OUT wire goes to a pin set with INPUT_PULLUP. The emitter and receiver face each other and nothing is in between. What does digitalRead() return?
- LOW (0)
- HIGH (1)
- Nothing, the pin is floating
Your alarm stops noticing people every afternoon, or behaves erratically, and the receiver sits near a sunny window. What is the best first thing to try?
- Turn the receiver away from the direct sun, or shade it
- Add a longer delay() at the end of loop()
- Swap the USB cable for a thicker one
Show the answer
Turn the receiver away from the direct sun, or shade it. Infrared comes from many sources, and SparkFun notes that the sun is very bright in the infrared [3]. Adafruit also warns that sunlight has infrared in it and that the setup works best in a darkened room [2]. Keeping direct sun off the receiver is the first precaution, and the Serial Monitor shows whether it was the cause.
The sketch prints "Beam broken" once per interruption, not hundreds of times a second. What makes that possible?
- delay(10) lasts exactly as long as one interruption
- Serial.println() ignores repeated text
- The code only prints when the state differs from the previous pass
Show the answer
The code only prints when the state differs from the previous pass. The sketch stores the previous state in lastState and prints only when the new state is different. Adafruit's own example for this sensor uses the same idea [2].
Sources
Show the 7 sources
- Adafruit, “IR Break Beam Sensor with Premium Wire Header Ends - 5mm LEDs”, product 2168 (emitter sends a human-invisible IR beam, receiver sensitive to the same light; beam broken when something not transparent to IR passes between; compared with PIR sensors and sonar modules; 5 mm version works up to 50 cm; 3.3 V to 5.5 V, 5 V recommended for range; open-collector output needs a pull-up, 10 kΩ if the board has no built-in one; emitter current 10 mA at 3.3 V and 20 mA at 5 V; response time under 2 ms; LED angle 10°) — https://www.adafruit.com/product/2168
- Adafruit, “IR Breakbeam Sensors”, Overview and Arduino pages (sunlight has infrared in it, so the setup works best in a darkened room; in ambient light, a distance sensor or PIR is suggested instead; emitter has two wires and receiver three; red, black and white or yellow signal wire; the two sides do not share power or ground; receiver is open collector and needs a pull-up; the reading is LOW when the beam is broken; example code compares the state with the previous one to print “Broken” and “Unbroken” once) — https://learn.adafruit.com/ir-breakbeam-sensors and https://learn.adafruit.com/ir-breakbeam-sensors/arduino
- SparkFun, “IR Communication” (infrared is light with a slightly longer wavelength, undetectable to the human eye; the sun, light bulbs and anything hot are very bright in the infrared; remote controls modulate at 38 kHz so the receiver can pick the signal out of ambient infrared; most cellphone cameras can see an IR LED faintly glowing) — https://learn.sparkfun.com/tutorials/ir-communication
- Adafruit, “IR Sensor”, Overview (photocells are good at yellow-green visible light and not good at infrared light) — https://learn.adafruit.com/ir-sensor/overview
- Espressif, Arduino-ESP32 documentation, “GPIO” (INPUT_PULLUP; internal pull-up and pull-down of about 45 kΩ; without a pull mode the pin stays high-impedance) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/gpio.html
- Espressif, ESP-IDF Programming Guide, “GPIO & RTC GPIO” (GPIO 34 to 39 can only be inputs and have no software-enabled pull-up or pull-down) — https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html
- Adafruit, “Adafruit HUZZAH32 ESP32 Feather: Pinouts” (the ESP32 runs on 3.3 V power and logic; GPIO pins are not 5 V safe unless stated otherwise) — https://learn.adafruit.com/adafruit-huzzah32-esp32-feather/pinouts