2N2222 nPN transistor with ESP32
How to connect a 2N2222 nPN transistor to an ESP32: the wiring, a sketch that works, and a simulator to try it in your browser before you build it.

2N2222 · TO-92 · β ≈ 180 · 600 mA
Wiring
| 2N2222 nPN transistor pin | ESP32 |
|---|---|
| E | GND |
| B | GPIO23 (through a 1 kΩ resistor) |
Run it in the labFree, no account needed. The same wiring, with the sketch already on the board.
Code
From the project ESP32 parking sensor: HC-SR04, three LEDs and a beeper. It also compiles in the Arduino IDE (ESP32 core 3.x) with the libraries it includes.
// Parking sensor: HC-SR04 + three LEDs + a buzzer that beeps faster as you get closer.
// The HC-SR04 runs on 5 V and its ECHO is 5 V too: R1/R2 (1 k / 2 k) bring it down to 3.3 V for the ESP32.
const int TRIG = 5, ECHO = 18;
const int LED_G = 25, LED_Y = 26, LED_R = 27, BUZZ = 23;
void setup() {
Serial.begin(115200);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(LED_G, OUTPUT); pinMode(LED_Y, OUTPUT); pinMode(LED_R, OUTPUT);
pinMode(BUZZ, OUTPUT);
}
long readCm() {
digitalWrite(TRIG, LOW); delayMicroseconds(2);
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000); // no echo within 30 ms: nothing in range
if (us == 0) return 999;
return us / 58; // 58 µs per cm, there and back
}
void loop() {
long cm = readCm();
Serial.print("Distance: "); Serial.print(cm); Serial.println(" cm");
digitalWrite(LED_G, cm >= 60);
digitalWrite(LED_Y, cm >= 25 && cm < 60);
digitalWrite(LED_R, cm < 25);
if (cm < 10) { // very close: a steady tone
digitalWrite(BUZZ, HIGH);
delay(100);
} else if (cm < 100) { // beep, with a gap that shrinks as you get closer
int gap = map(cm, 10, 100, 60, 600);
digitalWrite(BUZZ, HIGH); delay(60);
digitalWrite(BUZZ, LOW); delay(gap);
} else {
digitalWrite(BUZZ, LOW);
delay(100);
}
}
For teachers
The project runs in the browser on a laptop or a phone, so every student can build and test it before the class touches a real board. Assign it on the teacher's page and set what counts as done: a prediction, a hidden fault found, or a passing test sheet.