IR break-beam sensors: find when an object goes through a beam
A break-beam sensor is a pair of parts that point at each other. An emitter sends invisible infrared (IR) light to a receiver. When the receiver gets the light, its output stays in one state. When an object blocks the beam, the output changes immediately to the other state. This gives you a clean digital signal. You can use it to: count objects on a conveyor, find a marble in a track, make a finish-line timer, or measure speed with two beams (a photogate).

Photo: Adafruit (lady ada), CC BY-SA 3.0
Click the track to roll an object at the selected speed. The dashed pink lines show the IR beams. You cannot see real IR light with your eyes. Many phone cameras (frequently the front camera) show it as a weak glow.
This plot shows the receiver outputs as a logic analyzer shows them. The output is HIGH when the receiver gets the beam. The output goes LOW when the beam is broken (Adafruit-style receiver with a pull-up). Each falling edge is one interrupt.
Interrupt timestamps (from micros())
| # | tA (µs) | tB (µs) | Δt = tB − tA | v = d / Δt | Actual |
|---|---|---|---|---|---|
| Roll an object through both beams… | |||||
How it works
Emitter: an IR LED
The emitter is an infrared LED (about 940 nm). On Adafruit-style modules, it has a built-in resistor, so you can connect it directly to 3.3–5 V. The emitter is always on and has no signal wire. Usually, a higher supply voltage gives more range.
Receiver: open-collector output
The receiver contains a photo-detector and a transistor. The transistor can only pull the output to GND.
You supply the HIGH level with a pull-up resistor. Use INPUT_PULLUP (~45 kΩ in the ESP32) or an external
10 kΩ resistor to 3.3 V. The pull-up goes to 3.3 V, so the output is safe for the ESP32, also when the receiver uses 5 V.
Which output level shows a broken beam
In the Adafruit break-beam example, the output is LOW when the beam is broken. Other modules (and DIY
circuits) can have the opposite level. Examine your module: print digitalRead() while you block and unblock the beam.
Range & alignment
Adafruit gives about 25 cm for the 3 mm pair and 50 cm for the 5 mm pair. The LEDs send light mostly in one direction, so point them directly at each other. Attach them tightly (with hot glue or 3D-printed mounts). A small misalignment decreases the range very much.
Sunlight & reflections
Sunlight and incandescent bulbs contain much IR. This IR can “fill in” a broken beam, especially at long range. Put a short tube around the receiver to block other light. Shiny objects can also reflect the beam around a small object.
Photogate timing
Two beams at a known distance d give the speed: v = d / (tB − tA). If you use interrupts with
micros(), the timestamps are accurate to a few µs. Measure from the same edge (both falling).
Then the length of the object has no effect on the result.
Wiring
pinMode(27, INPUT_PULLUP) enables it.
The dashed resistor is an optional external pull-up. The internal pull-up is sufficient for short wires.
Add the 10 kΩ resistor if the wires are long or the signal has noise. You must add it if you use GPIO 34–39.Connections (Adafruit-style pair)
| Wire | Part | Connect to |
|---|---|---|
| Red | Emitter | 3V3 (or 5 V for more range) |
| Black | Emitter | GND |
| Red | Receiver | 3V3 (or 5 V) |
| Black | Receiver | GND |
| White | Receiver | GPIO 27 with pull-up (second gate: GPIO 26) |
The wire colors are different from seller to seller. Compare them with your product page. Do not use the input-only pins 34–39 if you do not add an external pull-up. These pins have no internal pull-up. Refer to GPIO.
Build steps
- Supply power to the emitter onlyLook at the emitter through a phone camera. Make sure that you see a weak purple glow.
- Connect the receiverRun the polling sketch below. Block the beam with your hand and look at the Serial Monitor.
- Attach and alignAttach the pair across the path at the height of the objects that you want to find.
- Change to interruptsUse interrupts for fast objects. To measure speed, add the second gate.
DIY alternative: IR LED + TSOP38238 receiver
A TV-remote style receiver only responds to IR that flashes at its carrier frequency (38 kHz for the TSOP38238), so sunlight and room light have almost no effect on it, and the range can be some meters. The LEDC peripheral of the ESP32 can make the 38 kHz carrier for an IR LED.
Important information
- The TSOP output is LOW when it receives the 38 kHz carrier. It is HIGH when the beam is blocked. This is the opposite of the Adafruit receiver above.
- Remote-control receivers, for example the TSOP382xx, have automatic gain control. This control can start to ignore a carrier that is on all the time. Then the beam looks “broken” after some time. Send the carrier in short bursts (for example, 600 µs on / 600 µs off) and sample during the burst. As an alternative, use a part for light barriers, for example the Vishay TSSP4038.
- Put a short tube on each side between the LED and the receiver. This makes a narrow, reliable beam.
Code
1 · Polling with state-change detection
This is the easiest start. The sketch does an action only when the reading changes.
breakbeam_poll.ino
const int BEAM_PIN = 27;
int lastState = HIGH;
void setup() {
Serial.begin(115200);
pinMode(BEAM_PIN, INPUT_PULLUP); // receiver output is open-collector
}
void loop() {
int state = digitalRead(BEAM_PIN);
if (state != lastState) { // do an action only on changes
if (state == LOW) Serial.println("Beam BROKEN");
else Serial.println("Beam restored");
lastState = state;
}
delay(5);
}
2 · Interrupt counter with debounce
This sketch finds objects that are too fast for polling. Keep the ISR very short. Do not call Serial in the ISR.
breakbeam_counter.ino
const int BEAM_PIN = 27;
const uint32_t DEBOUNCE_US = 2000; // ignore edges closer than 2 ms
volatile uint32_t count = 0; // volatile: the ISR changes it
volatile uint32_t lastCountUs = 0;
void IRAM_ATTR onBeamBroken() {
uint32_t now = micros();
if (now - lastCountUs > DEBOUNCE_US) {
count++;
lastCountUs = now;
}
}
void setup() {
Serial.begin(115200);
pinMode(BEAM_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BEAM_PIN), onBeamBroken, FALLING);
}
void loop() {
static uint32_t shown = 0;
noInterrupts(); // make a safe copy
uint32_t c = count;
interrupts();
if (c != shown) {
Serial.printf("Count: %lu\n", (unsigned long)c);
shown = c;
}
}
3 · Two-gate speed (photogate)
photogate_speed.ino
const int GATE_A = 27;
const int GATE_B = 26;
const float GATE_DISTANCE_M = 0.20; // measure this distance carefully
volatile uint32_t tA = 0, tB = 0;
volatile bool waitingForB = false, haveResult = false;
void IRAM_ATTR onGateA() {
if (!waitingForB && !haveResult) { tA = micros(); waitingForB = true; }
}
void IRAM_ATTR onGateB() {
if (waitingForB) { tB = micros(); waitingForB = false; haveResult = true; }
}
void setup() {
Serial.begin(115200);
pinMode(GATE_A, INPUT_PULLUP);
pinMode(GATE_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(GATE_A), onGateA, FALLING);
attachInterrupt(digitalPinToInterrupt(GATE_B), onGateB, FALLING);
}
void loop() {
if (haveResult) {
uint32_t dt = tB - tA; // unsigned math is correct when micros() wraps around
float speed = GATE_DISTANCE_M / (dt / 1e6f);
Serial.printf("dt = %lu us -> %.3f m/s\n", (unsigned long)dt, speed);
delay(300); // wait until the object is out of the gates
haveResult = false; // prepare for the next object
}
}
4 · 38 kHz carrier for a TSOP receiver
tsop_beam.ino
const int IR_LED_PIN = 25; // through 150 Ω to the IR LED
const int TSOP_PIN = 27; // TSOP OUT (LOW = carrier received)
void setup() {
Serial.begin(115200);
ledcAttach(IR_LED_PIN, 38000, 8); // 38 kHz, 8-bit duty
ledcWrite(IR_LED_PIN, 128); // 50 % duty square wave
pinMode(TSOP_PIN, INPUT_PULLUP);
}
void loop() {
bool beamOk = (digitalRead(TSOP_PIN) == LOW);
Serial.println(beamOk ? "beam OK" : "BLOCKED");
delay(50);
}
If the output shows “BLOCKED” after a clear beam for a few seconds, the cause is the gain control of the receiver
(refer to the information above). Send the carrier in bursts. Use ledcWrite(pin, 0) between the bursts.
Troubleshooting
The input is always LOW (or HIGH)
There are three possible causes. The signal has no pull-up (examine INPUT_PULLUP; pins 34–39 have no pull-up).
The emitter has no power (examine it with a phone camera). The two parts are not aligned.
The counter counts one object more than one time
When a round or semi-transparent object goes into the beam, the edges can change quickly many times. Debounce in the ISR (ignore edges that occur in a few ms). As an alternative, count only after the beam stays clear for some time.
Crashes or incorrect data with interrupts
Do not use Serial.print, delay() or long code in an ISR. Mark shared variables as
volatile. Disable interrupts for a short time while you copy these variables.
Resources
- Adafruit: IR Breakbeam Sensors guideWiring, ranges and example code for the 3 mm / 5 mm pairs.
- Vishay TSOP382xx datasheetPinout, carrier frequency and the necessary burst length.
- Arduino-ESP32 GPIO & interrupts
attachInterrupt(), pull-ups and pin modes. - ESP32 GPIOThe pins that have pull-ups and the pins that are input-only.
- PWM & LEDsThe LEDC peripheral that makes the 38 kHz carrier.
- OLED displayShow the count and the speed on a screen, as an alternative to the Serial Monitor.