Français

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.

Two halves, one invisible line Two panels. Top, beam clear: on the left, the IR emitter with two wires, red plus and black minus, sends an invisible infrared beam, drawn dashed, to the IR receiver on the right. The receiver has three wires: red plus, black minus, and a white or yellow signal wire called OUT. The two halves share no wire: the signal crosses the gap as light. Bottom, beam broken: a hand passes between the two halves and blocks the beam; the receiver no longer sees the emitter and reports it on OUT. FIG. 1 — TWO HALVES, ONE INVISIBLE LINEaBeam clearemitterIR+−red · blackreceiverIR+−OUTred · black · white or yellowinvisible infrared beamNo shared wire:the signal crosses the gap as light.HIGH · 1GPIO 32 readsbBeam brokenemitterIR+−red · blackreceiverIR+−OUTred · black · white or yellowno beam reaches itan object that blocks infraredLOW · 0GPIO 32 readsInfrared is light our eyes cannot see. The emitter is an infrared LED, not a laser.
Tap the diagram to open it full screen.

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.

Open-collector output and the pull-up IEC schematic, two states side by side. In each, the ESP32 holds an internal pull-up of about 45 kilohms, switched on by INPUT_PULLUP, between 3V3 and the GPIO 32 pin. The OUT wire joins GPIO 32 to the receiver. Inside the receiver, an output transistor can only connect OUT down to GND. Left, beam clear: the infrared reaches the detector, the transistor stays off, no current flows, and the pull-up holds the pin at 3.3 volts: digitalRead(32) returns HIGH, 1. Right, beam broken: the detector sees no infrared, the transistor turns on and pulls OUT to GND; a small current flows from 3V3 through the pull-up and the transistor to ground, and the pin reads LOW, 0. FIG. 2 — OPEN-COLLECTOR OUTPUT (IEC)aBeam clearESP323V3pull-up≈ 45 kΩINPUT_PULLUPGPIO 32digitalRead(32)HIGH (1)V ≈ 3.3 Vheld up by the pull-upOUTreceiverIRGNDIR beamoff: OUT left freeno currentbBeam brokenESP323V3pull-up≈ 45 kΩINPUT_PULLUPGPIO 32digitalRead(32)LOW (0)V ≈ 0 Vthe event: LOWOUTreceiverIRGNDobjecton: OUT → GNDcurrent flowsThe receiver can only pull OUT down to GND. The pull-up does the lifting.No pull-up board? Add 10 kΩ from OUT to 3V3 (never to 5 V). On the ESP32, INPUT_PULLUP is enough.Shaded line: the current path when the beam is broken.
Tap the diagram to open it full screen.
S1 wiring: IR receiver on 32, LED on 26, buzzer on 25 Breadboard seen from above, DevKitC across the centre gap, USB on the left, column j free. Eleven numbered wires. 1 black: GND pin to the top minus rail. 2 red: 3V3 pin to the top plus rail. The IR receiver sits above the board with its lens facing right: 3, its white or yellow OUT wire, goes into j13, next to GPIO 32; 4, its red wire, to the plus rail; 5, its black wire, to the minus rail. The IR emitter sits to its right, lens facing the receiver across a gap: 6, red, to the plus rail; 7, black, to the minus rail. 8 orange: GPIO 25 to row 30, the active buzzer's plus leg; its other leg is in row 33; 9 black: row 33 to the minus rail. 10 green: GPIO 26 to row 36; the 220 ohm resistor bridges rows 36 and 40; the LED's long leg is in row 40, its short leg in row 41; 11 black: row 41 to the minus rail. FIG. 3 — WIRING, BREADBOARD VIEW+−−+jihgfedcba15101319253033364044ENBOOT5VCMDD3D213GND121427262533323534VNVPEN3V3++RXTXgapIR receiverIR emitter1083456719112active buzzer220 ΩLED1black: GND pin → top − rail2red: 3V3 pin → top + rail3white or yellow: receiver OUT → j13 (GPIO 32)4red: receiver + → + rail5black: receiver − → − rail6red: emitter + → + rail7black: emitter − → − rail8orange: GPIO 25 → buzzer + (row 30)9black: buzzer − (row 33) → − rail10green: GPIO 26 → 220 Ω (row 36)11black: LED − (row 41) → − railEverything runs on 3V3. Face the two lenses at each other and fix them so they cannot wobble.Gap not to scale. Mission 01 uses 15 to 20 cm: test your own pair rather than trusting a number.
Tap the diagram to open it full screen.

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.

Break the beam (interactive)
Break the beam (interactive) Interactive. An IR emitter on the left and an IR receiver on the right face each other with a dashed infrared beam between them. Drag the hand down into the beam, or use the button below. Beam clear: GPIO 32 reads 1, digitalRead(32) returns HIGH, the LED and the buzzer are off. Beam broken: the pin reads 0, LOW, the LED and the buzzer switch on and the break counter goes up by one. A line draws the pin level over the last seconds. The Sunlight switch adds a bright infrared source next to the receiver: with nothing in the way the reading flickers, and with the hand in the beam it stays stuck at 1. This is an illustration of the idea, not a measurement of a real sensor. FIG. W — BREAK THE BEAMemitterTXreceiverRXOUT → GPIO 32infrared, invisibledrag10time →GPIO 32LED offbuzzer offBreaks counted: 0Beam clear: the pull-up holds GPIO 32 high, it reads 1.GPIO 321V ≈ 3.3 VdigitalRead(32)→ HIGH

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() says INPUT_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 after int 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.

  1. Longer gap. Move the halves apart a few centimetres at a time. At what distance does the count start misbehaving?
  2. Thin objects. Try a sheet of paper, a clear plastic cup, your hand. Which ones break the beam?
  3. 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.

  1. 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
    Show the answer

    HIGH (1). The receiver's output is open collector: it can pull the wire down to ground but not push it up, so the pull-up holds the wire high while the beam is clear [1][2][5]. Breaking the beam makes the reading drop to LOW [2].

  2. 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.

  3. 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
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.