Basics · 11 min read

Phototransistor Arduino Guide: Photodiode vs LDR, Wiring, Code

Phototransistor Arduino: how it differs from a photodiode and LDR, choosing the load resistor, IR vs visible types, light gate, RPM counter, ESP32 and Pico.

A phototransistor is a transistor that lets more current through as more light falls on it; its base is driven by light instead of a wire. Its sibling, the photodiode, is a diode in a transparent package that turns light directly into a small current. Both measure light like an LDR, but they respond thousands of times faster. These two parts are at work inside infrared obstacle sensors, light gates, tachometers, encoders and TV remote receivers.

In this article you'll learn how photodiodes and phototransistors work, how they differ from an LDR in speed and linearity, the infrared (IR) and visible-light types, and how to choose the load resistor when you connect them to an Arduino. Then you'll measure speed with two light gates, count motor RPM with an ESP32, decode a remote control signal with a bare phototransistor and read the same sensor in MicroPython on a Raspberry Pi Pico.

TCRT5000 module with an infrared LED and a phototransistor
Inside the TCRT5000 an IR LED and a phototransistor sit side by side.

What are a photodiode and a phototransistor, and how do they work?

A photodiode is a diode with a PN junction, or a PIN structure with an undoped layer in the middle. When light hits the junction, photons create electron-hole pairs and a photocurrent proportional to the light flows through the diode. A photodiode is usually reverse biased: the cathode goes to the positive rail and the anode to ground through a resistor. In this mode the current tracks light intensity almost perfectly linearly and the response time is in the nanosecond range. The popular BPW34 PIN photodiode gives about 50 µA at 1 mW/cm² of infrared light, while its dark leakage current is only a few nA. You can also use a photodiode with no supply at all: in this photovoltaic mode it produces a few hundred mV like a tiny solar cell, but it responds more slowly.

A phototransistor is an NPN transistor whose base-collector junction has been enlarged and exposed to light. The photocurrent generated in this junction flows into the base, and the transistor amplifies it by its gain (hFE, typically 100–1000). The result is hundreds of times more current than a photodiode gives in the same light, milliamps instead of microamps, so a single resistor produces a voltage the Arduino can read. The price is speed and linearity: because of the large base capacitance, rise and fall times are between a few µs and 20 µs, and the gain shifts a little with light and temperature. Most phototransistors have no base lead; they look like a two-legged LED, and the legs are the collector (C) and the emitter (E). The basics are covered in the what is a diode and what is a transistor articles.

How they differ from an LDR: speed and linearity

An LDR (photoresistor) is a piece of cadmium sulfide whose resistance changes with light. It is cheap and easy to use, but slow: the common GL5528 takes about 20 ms to react to light and 30 ms or more to return to dark. That means it can follow only a few dozen changes per second; it misses a 38 kHz remote signal or a beam interrupted hundreds of times a second. Its resistance also changes logarithmically with light, two samples of the same model give different values, and it 'remembers' bright light for a while. A photodiode, by contrast, is a linear and repeatable sensor whose current rises tenfold when light rises tenfold. The phototransistor sits in the middle between speed and sensitivity. The table below puts all three side by side.

FeatureLDRPhotodiodePhototransistor
PrincipleCdS whose resistance changes with lightPN/PIN junction that generates current from lightTransistor that amplifies the photocurrent with its own gain
Response time10–100 ms1 ns – 1 µs (PIN type)2–20 µs
Output (room light)Resistance about 1–10 kΩA few µAHundreds of µA to a few mA
LinearityPoor (logarithmic)Excellent (several decades)Moderate, saturates in bright light
SpectrumVisible, peak about 540 nm400–1100 nm depending on model570 nm (visible) or 850–940 nm (IR)
Arduino connectionVoltage dividerLarge resistor or op-ampSingle load resistor
Typical useNight light, dusk switchPrecise measurement, fast data, lux meterLight gate, encoder, obstacle sensor

IR and visible-light types

Silicon photodiodes and phototransistors naturally see from 400 to 1100 nm, and they are most sensitive in the near infrared (about 850–950 nm). Manufacturers shape this sensitivity with the package color and added filters. Parts in a black or dark package have a daylight filter: they block visible light and pass only the 850 or 940 nm light of an IR LED. Obstacle sensors, light gates and remote receivers use these because room lamps barely affect them. Parts in a clear package see both visible light and IR. Models sold as ambient light sensors, such as the TEPT5600, have a filter that gives a curve similar to the human eye with peak sensitivity at 570 nm; choose these for screen brightness control and lux measurement. Remember to match the receiver's wavelength to the emitter: a 940 nm LED needs a filtered receiver rated for 940 nm.

TypeExample partPeak wavelengthWhere it is used
PIN photodiode (clear)BPW34About 900 nm (430–1100 nm)Lux meter, fast light measurement
Photodiode with daylight filterBPW41N, SFH 205 FAbout 950 nmIR data links, remote receivers
IR phototransistor (filtered)SFH 309 FA, PT333 series880–940 nmLight gate, obstacle and lap sensor
Visible-light phototransistorTEPT5600, TEPT4400570 nm (eye-like)Ambient light, automatic brightness
Ready-made optical sensor (LED + phototransistor)TCRT5000 (reflective), ITR9606 (slotted)940–950 nmLine following, encoder disc, RPM counting

Connecting to an Arduino: choosing the load resistor

A phototransistor behaves like a current source; for the Arduino to read it, you have to turn that current into a voltage with a load resistor. There are two ways to wire it. With the load on the emitter (common collector), the collector goes to 5 V and the emitter goes both to the analog pin and through RL to GND; the pin voltage rises with light, and this is the most intuitive wiring for analog measurement. With the load on the collector (common emitter), RL sits between 5 V and the collector, the emitter goes to GND and the pin reads the collector. Now the voltage falls as light rises; since the output goes HIGH when the beam is blocked, light gates and digital counters usually use this one. A photodiode is wired with the same logic, but reversed: cathode to 5 V, anode to the pin and RL.

ConnectionArduino UnoESP32Raspberry Pi Pico
Phototransistor C (analog circuit)5V3V33V3(OUT), pin 36
Phototransistor E + 10 kΩ to GNDA0GPIO 34 (ADC1)GP26 (ADC0)
Photodiode cathode / anode + 1 MΩ to GND5V / A13V3 / GPIO 353V3 / GP27 (ADC1)
Light gate or slotted module outputD2 (second gate D3)GPIO 4GP15
IR LED (with series resistor)5V, 220 Ω3V3, 100 Ω3V3, 100 Ω
GNDGNDGNDGND

The rule for choosing the load resistor is simple: the output voltage is roughly V = I × RL, and when it gets to about 0.3 V below the supply the transistor saturates, so more light is no longer measured. Choose RL so that I × RL stays below the supply even in the brightest light you want to measure. The TEPT5600, for example, gives about 70 µA at 20 lx and about 350 µA at 100 lx. With 10 kΩ you read 3.5 V at 100 lx, but on a desk brighter than 150 lx the sensor saturates; for a normally lit room 1–2.2 kΩ is a better choice. A larger resistor raises sensitivity but lowers speed, because RL forms an RC circuit with the phototransistor's capacitance. You can do the math quickly with the Ohm's law calculator.

Load resistorSensitivitySpeedGood for
1 kΩLow, does not saturate in bright lightFastest (a few µs)Remote signals, fast encoders, sunlight
4.7–10 kΩMediumAbout 10–50 µsLight gates, room light, RPM counting
47–100 kΩHigh, separates dim levelsSlow (hundreds of µs)Night measurement, weak IR reflection
1 MΩ (photodiode)Reads µA-level currentMilliseconds (with the ADC)Simple photodiode measurement

Because a photodiode gives microamps, it needs a large resistor such as 1 MΩ; 5 µA × 1 MΩ = 5 V. Such a high-impedance source strains the Arduino's ADC, since the ATmega328P wants a source impedance of 10 kΩ or less. The simple fix is to read the pin once and discard the result before measuring, or to put a 100 nF capacitor across RL. If you need speed and accuracy, connect the photodiode to a transimpedance amplifier: the photodiode goes to the inverting input of an op-amp, a feedback resistor Rf goes between the output and the inverting input, and the output is Vout = Ip × Rf. Because the voltage across the photodiode is held at zero, both linearity and speed are preserved. Pick a single-supply, rail-to-rail op-amp such as the MCP6001 and prevent oscillation with a few pF across Rf.

The most common mistake is mixing up polarity. If you connect a photodiode forward like an LED, with the anode to the positive rail, the diode conducts and light changes almost nothing; the cathode must go to the positive side. The pinout of phototransistors also varies by manufacturer, so check the datasheet. A phototransistor connected backwards is not damaged at 5 V, it just barely reacts to light; flip the legs and try again.

Reading light levels with an Arduino

C++ (Arduino IDE)
1// Fototransistör ve fotodiyot ile ışık ölçümü / Light measurement with a phototransistor and a photodiode
2const int PT_PIN = A0;              // fototransistör emitörü, 10 kΩ ile GND'ye / phototransistor emitter, 10 kΩ to GND
3const int PD_PIN = A1;              // fotodiyot anodu, 1 MΩ ile GND'ye / photodiode anode, 1 MΩ to GND
4const float VREF = 5.0;             // Uno ADC referansı / Uno ADC reference
5const float R_PT = 10000.0;         // fototransistör yük direnci (Ω) / phototransistor load resistor (Ω)
6const float R_PD = 1000000.0;       // fotodiyot yük direnci (Ω) / photodiode load resistor (Ω)
7
8float readVolts(int pin) {
9  analogRead(pin);                  // boş okuma: örnekleme kondansatörü dolsun / dummy read: let the sample cap settle
10  delayMicroseconds(200);
11  long sum = 0;
12  for (int i = 0; i < 16; i++) sum += analogRead(pin);  // 16 ölçüm ortalaması / average of 16 readings
13  return sum / 16.0 * VREF / 1023.0;
14}
15
16void setup() {
17  Serial.begin(9600);
18}
19
20void loop() {
21  float vPt = readVolts(PT_PIN);
22  float vPd = readVolts(PD_PIN);
23  float iPt = vPt / R_PT * 1e6;     // akım µA, Ohm yasası / current in µA, Ohm's law
24  float iPd = vPd / R_PD * 1e6;
25
26  Serial.print("Fototransistor: ");
27  Serial.print(vPt, 2);
28  Serial.print(" V  ");
29  Serial.print(iPt, 0);
30  Serial.print(" uA   |   Fotodiyot: ");
31  Serial.print(vPd, 2);
32  Serial.print(" V  ");
33  Serial.print(iPd, 2);
34  Serial.println(" uA");
35
36  if (vPt > 4.6) {
37    // doyum: yük direncini küçült / saturation: use a smaller load resistor
38    Serial.println("Uyari: fototransistor doyumda / Warning: phototransistor saturated");
39  }
40  delay(500);
41}

For the circuit, connect the phototransistor's collector to 5V and its emitter to A0, with 10 kΩ between A0 and GND; connect the photodiode's cathode to 5V and its anode to A1, with 1 MΩ between A1 and GND. The code averages 16 readings per pin and prints the result as both voltage and current. The current is the voltage divided by the load resistor, so you can directly compare tests with different resistors. The dummy read before each measurement gives the ADC's sampling capacitor time to charge from the 1 MΩ source. In room light you'll see the phototransistor deliver hundreds of µA and the photodiode only a few µA; that difference of hundreds of times is the transistor's gain. If you watch the values in the Serial Plotter, you'll also notice the photodiode follows changes in light with a smoother, more linear curve.

Light gate: counting passes and measuring speed

A light gate is an IR LED and a phototransistor facing each other. When nothing is in between, the beam reaches the phototransistor and in the common-emitter wiring the output is LOW; the moment an object breaks the beam, the output goes HIGH. By catching this rising edge with an interrupt you can count what passes through the gate, and with two gates you can measure speed: speed = distance between gates / time between the two breaks. In the code below the gates are 20 cm apart on D2 and D3; each gate uses 10 kΩ as RL and 220 Ω for the IR LED. Since micros() has 4 µs resolution, toy car or marble speeds are easy to measure; an object at 2 m/s crosses 20 cm in 100 ms. Interrupts are explained in detail in the Arduino interrupt article.

C++ (Arduino IDE)
1// İki ışık kapısıyla hız ölçümü / Speed measurement with two light gates
2// Işın kesilince çıkış HIGH olur (ortak emitör, 10 kΩ) / Output goes HIGH when the beam is blocked (common emitter, 10 kΩ)
3const byte GATE_A = 2;              // birinci kapı, INT0 / first gate, INT0
4const byte GATE_B = 3;              // ikinci kapı, INT1 / second gate, INT1
5const float DISTANCE_M = 0.20;      // kapılar arası mesafe (m) / distance between the gates (m)
6const unsigned long TIMEOUT_US = 3000000UL;  // 3 s içinde B gelmezse sıfırla / reset if B does not fire within 3 s
7
8volatile unsigned long tA = 0;
9volatile unsigned long tB = 0;
10unsigned int passes = 0;
11
12void onGateA() {
13  if (tA == 0) tA = micros();       // ilk kesilme anı / moment of the first break
14}
15
16void onGateB() {
17  if (tA != 0 && tB == 0) tB = micros();
18}
19
20void resetGates() {
21  noInterrupts();
22  tA = 0;
23  tB = 0;
24  interrupts();
25}
26
27void setup() {
28  Serial.begin(9600);
29  pinMode(GATE_A, INPUT);           // yük direnci devrede / load resistor is on the board
30  pinMode(GATE_B, INPUT);
31  attachInterrupt(digitalPinToInterrupt(GATE_A), onGateA, RISING);
32  attachInterrupt(digitalPinToInterrupt(GATE_B), onGateB, RISING);
33  Serial.println("Isik kapisi hazir / Light gate ready");
34}
35
36void loop() {
37  noInterrupts();                   // çok baytlı değişkenleri güvenle kopyala / copy multi-byte variables safely
38  unsigned long a = tA;
39  unsigned long b = tB;
40  interrupts();
41
42  if (a != 0 && b != 0) {
43    float dt = (b - a) / 1000000.0; // saniye / seconds
44    float speed = DISTANCE_M / dt;  // m/s
45    passes++;
46    Serial.print("Gecis / pass ");
47    Serial.print(passes);
48    Serial.print(": ");
49    Serial.print(dt * 1000.0, 2);
50    Serial.print(" ms  ");
51    Serial.print(speed, 3);
52    Serial.print(" m/s  ");
53    Serial.print(speed * 3.6, 2);
54    Serial.println(" km/h");
55    delay(300);                     // cisim kapılardan tamamen çıksın / let the object clear both gates
56    resetGates();
57  } else if (a != 0 && micros() - a > TIMEOUT_US) {
58    Serial.println("Zaman asimi / Timeout: gate B not seen");
59    resetGates();
60  }
61}
The narrower the beam, the sharper the measurement. Put the phototransistor inside a 1–2 cm piece of black straw or heat-shrink tubing; it blocks ambient light and brings the moment the beam is broken close to millimeter precision. If the LED and receiver are more than 5 cm apart, lower the LED resistor to 150 Ω (about 25 mA) for a stronger beam; check the value with the LED resistor calculator.

Counting RPM with an ESP32

To measure a motor's speed, mount a slotted disc on its shaft and let the disc spin through a U-shaped slotted optical sensor. Ready-made 'speed sensor' modules pair this sensor with an LM393 comparator and provide a digital DO output. The disc produces one pulse per slot; with a 20-slot disc, one revolution is 20 pulses. Formula: RPM = pulses × 60 / (slots × measurement time). Power the module from the ESP32's 3V3 pin so the DO output never exceeds 3.3 V. Most LM393 modules have no hysteresis and may chatter at the slot edge; the 200 µs filter in the code rejects these false pulses and still allows measurements up to 15,000 RPM. The interrupt function is placed in RAM with IRAM_ATTR and the counter is protected with a portMUX, so the value is not corrupted while the main loop reads and resets it.

C++ (Arduino IDE)
1// ESP32 ile yarıklı disk ve optik sensörle devir ölçümü / RPM measurement with a slotted disc and an optical sensor on ESP32
2const int SENSOR_PIN = 4;            // LM393 modülünün DO çıkışı / DO output of the LM393 module
3const int SLOTS = 20;                // diskteki yarık sayısı / number of slots in the disc
4const uint32_t MIN_GAP_US = 200;     // daha kısa darbeler titreşimdir / shorter pulses are bounce
5
6volatile uint32_t pulses = 0;
7volatile uint32_t lastPulseUs = 0;
8portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
9
10void IRAM_ATTR onPulse() {           // kesme kodu RAM'de / interrupt code lives in RAM
11  uint32_t now = micros();
12  if (now - lastPulseUs >= MIN_GAP_US) {
13    portENTER_CRITICAL_ISR(&mux);
14    pulses++;
15    portEXIT_CRITICAL_ISR(&mux);
16    lastPulseUs = now;
17  }
18}
19
20void setup() {
21  Serial.begin(115200);
22  pinMode(SENSOR_PIN, INPUT_PULLUP);
23  attachInterrupt(digitalPinToInterrupt(SENSOR_PIN), onPulse, RISING);
24}
25
26void loop() {
27  static uint32_t lastMs = millis();
28  uint32_t nowMs = millis();
29  if (nowMs - lastMs >= 1000) {      // her saniye hesapla / compute every second
30    portENTER_CRITICAL(&mux);
31    uint32_t count = pulses;
32    pulses = 0;
33    portEXIT_CRITICAL(&mux);
34    float seconds = (nowMs - lastMs) / 1000.0;
35    lastMs = nowMs;
36    float rpm = count * 60.0 / (SLOTS * seconds);   // RPM = darbe x 60 / (yarık x süre) / pulses x 60 / (slots x time)
37    Serial.printf("Darbe / pulses: %lu  Devir / speed: %.0f RPM\n", (unsigned long)count, rpm);
38  }
39}

Seeing a remote control signal

TV remotes send data by switching a 940 nm IR LED on and off at 38 kHz. Normally this signal is decoded by an IR receiver such as the TSOP1838, which is really a package containing a photodiode, an amplifier, a 38 kHz band-pass filter and a demodulator. With a bare phototransistor you can see the same signal in raw form. Wire the phototransistor in common emitter, use a 1 kΩ load resistor for a fast response and connect it to D2. The code groups the moments when the output is LOW into 'bursts' separated by 300 µs gaps and prints the length of each burst and the gap after it. With the NEC protocol you'll see a header burst of about 9000 µs, a 4500 µs gap and then short 560 µs bursts. Without a filter and amplifier the range is only 5–15 cm, which is ideal for testing whether a remote works or learning the protocol.

C++ (Arduino IDE)
1// Çıplak fototransistörle kumanda sinyalini çözümleme / Analysing a remote signal with a bare phototransistor
2// Ortak emitör, 1 kΩ yük: IR gelince D2 LOW olur / Common emitter, 1 kΩ load: D2 goes LOW when IR arrives
3const byte IR_PIN = 2;
4const unsigned long GAP_US = 300;      // bu kadar karanlık = patlama bitti / this long dark = burst over
5const unsigned long END_US = 20000;    // 20 ms karanlık = kod bitti / 20 ms dark = code over
6const int MAX_BURSTS = 40;
7
8unsigned int marks[MAX_BURSTS];        // patlama süreleri (µs) / burst lengths (µs)
9unsigned int spaces[MAX_BURSTS];       // boşluk süreleri (µs) / gap lengths (µs)
10
11void setup() {
12  Serial.begin(115200);
13  pinMode(IR_PIN, INPUT);
14  Serial.println("Kumandayi 5-10 cm'den sensore tut / Hold the remote 5-10 cm from the sensor");
15}
16
17void loop() {
18  if (digitalRead(IR_PIN) == HIGH) return;   // IR yok, bekle / no IR, keep waiting
19
20  int n = 0;
21  unsigned long markStart = micros();
22  unsigned long lastLight = markStart;
23  unsigned long spaceStart = 0;
24  bool inMark = true;
25
26  while (n < MAX_BURSTS) {
27    unsigned long now = micros();
28    bool light = (digitalRead(IR_PIN) == LOW);
29    if (inMark) {
30      if (light) {
31        lastLight = now;
32      } else if (now - lastLight > GAP_US) {   // patlama bitti / burst finished
33        marks[n] = lastLight - markStart;
34        spaceStart = lastLight;
35        inMark = false;
36      }
37    } else if (light) {                       // yeni patlama başladı / a new burst started
38      spaces[n] = now - spaceStart;
39      n++;
40      if (n >= MAX_BURSTS) break;
41      markStart = now;
42      lastLight = now;
43      inMark = true;
44    } else if (now - spaceStart > END_US) {   // uzun sessizlik: kod bitti / long silence: code over
45      spaces[n] = 0;
46      n++;
47      break;
48    }
49  }
50
51  Serial.print("Patlama sayisi / bursts: ");
52  Serial.println(n);
53  for (int i = 0; i < n; i++) {
54    Serial.print(marks[i]);
55    Serial.print(" us isik / light, ");
56    Serial.print(spaces[i]);
57    Serial.println(" us bosluk / gap");
58  }
59  if (n > 0 && marks[0] > 8000 && marks[0] < 10000) {
60    Serial.println("~9 ms baslik: buyuk olasilikla NEC / ~9 ms header: probably NEC");
61  }
62  Serial.println();
63  delay(200);
64}

Raspberry Pi Pico and MicroPython

The Pico runs on 3.3 V, so connect the phototransistor's collector to the 3V3(OUT) pin and the emitter to GP26 (ADC0) and through 10 kΩ to GND. read_u16() returns 0–65535; multiply by 3.3 and divide by 65535 to get volts, then divide by the load resistor to get current. In the same code a light gate on GP15 is counted with an interrupt; the 20 ms filter stops the chatter at an object's edge from being counted as several passes. The Pico's ADC is a little noisy near zero, so the code averages 16 readings.

MicroPython
1# Raspberry Pi Pico: fototransistör ve ışık kapısı / phototransistor and light gate
2from machine import ADC, Pin
3import time
4
5sensor = ADC(26)               # GP26 = ADC0, emitör + 10 kΩ GND'ye / emitter + 10 kΩ to GND
6gate = Pin(15, Pin.IN)         # ışık kapısı çıkışı, kesilince HIGH / light gate output, HIGH when blocked
7count = 0
8last_ms = 0
9
10def on_break(pin):
11    global count, last_ms
12    now = time.ticks_ms()
13    if time.ticks_diff(now, last_ms) > 20:   # 20 ms titreşim filtresi / 20 ms bounce filter
14        count += 1
15        last_ms = now
16
17gate.irq(trigger=Pin.IRQ_RISING, handler=on_break)
18
19while True:
20    total = 0
21    for _ in range(16):                      # 16 ölçüm ortalaması / average of 16 readings
22        total += sensor.read_u16()
23    volts = total / 16 * 3.3 / 65535         # 0-65535 -> 0-3.3 V
24    current_ua = volts / 10000 * 1e6         # I = V / R (µA)
25    print("Isik / light: {:.2f} V  {:.0f} uA  Gecis / passes: {}".format(volts, current_ua, count))
26    time.sleep(0.5)

Project ideas with phototransistors and photodiodes

  • People and product counter: Put a light gate across a door or a conveyor and count what passes; see the Arduino people counter article for details.
  • Marble speedometer: Use two gates to measure a marble rolling down a ramp and turn it into a physics experiment about friction.
  • Motor tachometer: Measure the speed of a fan, drill or wheel with a slotted disc and an ESP32 and show it on a display.
  • Line-following robot: Follow a black line with reflective TCRT5000 sensors.
  • Laser alarm: Use a laser module instead of an IR LED and build a security line that sounds when the beam is broken.
  • Remote tester: Build a small tool that lights an LED when a button is pressed and shows the burst lengths.
  • Automatic brightness: Measure ambient light with a TEPT5600 and adjust an LED strip's brightness with PWM.

Common mistakes and fixes

SymptomLikely causeFix
Value always 5 V or 1023Load resistor too large, sensor saturatedUse a smaller RL (1–2.2 kΩ instead of 10 kΩ)
Light changes almost nothingPhotodiode forward biased or phototransistor reversedPut the photodiode's cathode to positive, flip the phototransistor's legs
Light gate triggers when the room lamp turns onUnfiltered (clear) receiver sees ambient lightUse a black-package IR receiver and shade it with a tube
100 Hz ripple in the readingsThe fast sensor sees mains-powered lamps flickerAverage readings over 20 ms
RPM two or three times too highThe comparator chatters at the slot edgeFilter short pulses in the interrupt, add 10 nF between DO and GND
ESP32 value goes wrong when Wi-Fi is onSensor is on an ADC2 pinUse ADC1 pins (GPIO 32–39)

Photodiodes and phototransistors are the fastest and cheapest sensors you can use not just to measure light, but to time, count and receive data with it; the load resistor logic you learned here applies to every optical sensor. In the BlueGrays app you can open the LDR night light, laser security system and TCRT5000 projects with step-by-step circuit diagrams and ready-to-use code, and combine them with the light gate from this article.

Frequently asked questions

What is the difference between a phototransistor and a photodiode?

A photodiode turns light directly into a small current; it is very fast and linear, but the current is in the microamp range. A phototransistor amplifies the same photocurrent hundreds of times with its own gain, so a single resistor is enough to read it. In return it is slower and saturates in bright light.

How do you connect a phototransistor to an Arduino?

The easiest way is collector to 5 V, emitter to an analog pin and through a 10 kΩ resistor to GND; the voltage rises with light. For digital use, the resistor goes between 5 V and the collector and the pin reads the collector; the output goes HIGH when the beam is blocked.

What resistor should I use with a phototransistor?

In the brightest light you want to measure, current times resistance must stay below the supply voltage. Start with 4.7–10 kΩ for light gates, 1 kΩ for sunlight and fast signals and 47–100 kΩ for dim environments. A larger resistor raises sensitivity but slows the response.

Why is a photodiode reverse biased?

With reverse bias, only the photocurrent generated by light flows through the diode, and it changes linearly with light. The reverse voltage also lowers the junction capacitance, so the diode responds faster. A forward-biased photodiode simply conducts like a normal diode and the effect of light is lost.

Should I use an LDR or a phototransistor?

An LDR is enough for slowly changing jobs such as a night light. For light gates, RPM counting, encoders or remote signals, where many changes per second must be followed, choose a phototransistor. If you need accurate readings, a photodiode or a digital light sensor such as the BH1750 is better.

Does a phototransistor work in sunlight?

It does, but sunlight contains a lot of IR, so the sensor saturates easily and IR beam systems go blind. Outdoors, lower the load resistor to 1 kΩ, use a black-package receiver with a daylight filter and shade it with a tube. For reliable results, modulate the IR LED and detect only that frequency.

See all projects
Measuring Light Intensity with an LDR
AR-11Beginner

Measuring Light Intensity with an LDR

Want to see how bright your room is as a number? The LDR, a small part that reacts to light, measures the light around it, and the Arduino writes the value to your computer screen every half second.

4.5(86)
154
Night Light with Ldr
AR-12Beginner

Night Light with Ldr

A little night light that turns on by itself when it gets dark and goes off when morning comes.

4.7(107)
248
Reading Light Intensity with the ESP32 LDR Module
ES-11Beginner

Reading Light Intensity with the ESP32 LDR Module

Real-time monitoring of the LDR module's raw ADC value and relative light percentage calculated from dark and light reference values in the Serial Monitor. This percentage is not a lux measurement. Teaches the module’s calibration logic. It is ideal to complete this before Project 10, as it is used to determine the threshold value.

4.6(36)
56
Laser Warning System
AR-22Intermediate
Premium

Laser Warning System

You set up an invisible beam fence, just like in the movies. A laser shines onto a light sensor on the other side; the moment someone walks through and breaks the beam, the LED lights up and the…

4.8(65)
83
Laser Security System
AR-23Advanced
Premium

Laser Security System

Just like the laser heist scenes in films: a laser beam shines on a light sensor, and the moment someone steps in and breaks the beam, the red LED lights up and the buzzer starts sounding.

4.8(61)
78
Reading Reflection (Proximity) with TCRT5000
AR-77Intermediate
Premium

Reading Reflection (Proximity) with TCRT5000

With a small sensor that sends out invisible light and measures how much bounces back, you can detect the surface in front of it.

4.6(33)
43
TCRT5000 Black and White Surface Detection
AR-78Intermediate
Premium

TCRT5000 Black and White Surface Detection

With the little sensor that acts as the eye of line-following robots, you can tell whether the floor is black or white.

4.7(40)
49
Reading IR Remote Control Codes
AR-16Beginner
Premium

Reading IR Remote Control Codes

Every button on your TV remote sends a secret code using light you cannot see. The infrared receiver catches that light, and the Arduino writes the code of every button you press on your computer…

4.5(39)
55