Piezo Sensor Arduino: Knock Detection, 1 MΩ Resistor and Code
Piezo sensor Arduino guide: 1 MΩ parallel resistor and Zener protection, analog threshold knock detection, strength table, knock lock, drum pad, ESP32 and Pico.
A piezo sensor with Arduino is the cheapest and most sensitive way to measure vibration and knocks. A piezo disc is a thin ceramic layer glued to a brass plate, and it produces a voltage between its two leads when it bends: tapping the table with a finger gives a few hundred millivolts, while a hard knock can produce tens of volts. Limit that voltage with a parallel resistor, feed it to an analog pin, and the Arduino can tell both that a knock happened and how hard it was.
In this guide you'll see how a piezo disc works, why it needs a 1 MΩ parallel resistor and a protection part, how to wire it to an Arduino Uno, ESP32 and Raspberry Pi Pico, and the right way to detect knocks with a threshold. Then, step by step with code, we'll cover a knock strength table, a lock that opens when you knock a certain rhythm on the door, a drum pad that turns hit strength into MIDI, and the difference when you use the same disc as a buzzer.

What is a piezo disc sensor and how does it work?
With the piezoelectric effect, some crystals and ceramics build up electric charge on their surfaces when they are squeezed or bent. In the piezo discs used in hobby electronics, the material is usually PZT (lead zirconate titanate) ceramic, glued as a thin layer onto a brass plate. When a knock bends the disc, a voltage appears between the ceramic and the brass; as the disc springs back, the voltage reverses. So the output is a short, two-way, decaying oscillation. Electrically, the disc behaves like a small capacitor: a 27 mm disc has about 20 nF. The effect also works in reverse: apply a voltage and the disc flexes, which is why piezo discs also make sound as passive buzzers.
| Feature | Typical value | What it means in practice |
|---|---|---|
| Common diameters | 20, 27 and 35 mm | 27 mm is the most common size for both sensors and buzzers |
| Capacitance (27 mm) | About 20 nF | With 1 MΩ it forms a 20 ms time constant |
| Resonant frequency | 27 mm: about 4.6 kHz, 35 mm: about 2.8 kHz | As a buzzer it is loudest at this frequency |
| Output voltage | 0.1–1 V on a light touch, 10 V and more on a hard knock | Never connect it to an analog pin without protection |
| Output shape | Decaying oscillation in both positive and negative directions | The negative half must be limited too |
| Power supply | Not needed | The disc makes its own voltage; it is a passive sensor |
The 1 MΩ parallel resistor and protection circuit
If you connect a piezo disc straight to an analog pin, you get two problems. First, the charge on the disc has nowhere to go; the pin acts as if it were floating and the readings wander randomly. Second, the high voltage of a hard knock can damage the pin. A 1 MΩ resistor connected in parallel across the disc solves the first problem: it bleeds off the charge and pulls the signal to zero. Together with the disc's 20 nF, 1 MΩ forms a time constant of about 20 ms (you can try it with the RC time constant calculator), so the signal dies away within a few tens of milliseconds. Drop the resistor to 100 kΩ and the sensor gets less sensitive but recovers faster; raise it to 10 MΩ and it catches even very light touches, but becomes slower. For the second problem, add a 1–10 kΩ series resistor between the disc and the pin and a Zener diode between the pin and GND (5.1 V for the Uno, 3.3 V for the ESP32 and Pico). Hard knocks are then clipped at a safe level, and the negative peak is held at about -0.7 V as the Zener conducts in the forward direction.
| Part | Value | Function |
|---|---|---|
| Parallel resistor (across the disc) | 1 MΩ | Bleeds off the charge, pulls the signal to zero, sets the sensitivity |
| Series resistor (between disc and pin) | 1–10 kΩ | Limits the current while clipping |
| Zener diode (between pin and GND) | Uno: 5.1 V, ESP32/Pico: 3.3 V | Clips the positive peak, holds the negative peak around -0.7 V |
| Alternative: two Schottky diodes | BAT85 or 1N5817 | One from pin to VCC, one from GND to pin; keeps the peak 0.3 V above the supply and 0.3 V below GND |
Piezo wiring table: Arduino Uno, ESP32 and Pico
| Connection | Arduino Uno | ESP32 | Raspberry Pi Pico |
|---|---|---|---|
| Piezo red wire (+) | To A0 through 10 kΩ | To GPIO 34 through 10 kΩ | To GP26 (ADC0) through 10 kΩ |
| Piezo black wire (-) | GND | GND | GND |
| 1 MΩ resistor | Between piezo + and GND | Between piezo + and GND | Between piezo + and GND |
| Zener diode (cathode to pin) | 5.1 V: between A0 and GND | 3.3 V: between GPIO 34 and GND | 3.3 V: between GP26 and GND |
| Knock indicator LED | D13 (onboard) | GPIO 2 (onboard on most boards) | GP25 (Pico onboard LED) |
| MOSFET gate for the lock | D9 | Not in this example | Not in this example |
Knock detection with an analog threshold: step by step
- Stick the disc to a hard surface (table, door, box lid) with double-sided tape or hot glue; the tighter the contact, the stronger the signal.
- Connect the 1 MΩ resistor between the disc's two wires, and the series resistor and Zener as shown in the table.
- Upload the sketch below and open the Serial Monitor at 115200 baud.
- Look at the values without touching anything: 0–5 is noise. Set ESIK clearly above the noise (e.g. 40).
- Knock with different strengths and note the peak values; adjust the soft, medium and hard limits to your own setup.
- If you see two lines for one knock, the disc is ringing: raise OLU_SURE from 80 ms to 120–150 ms.
1// Piezo disk ile vuruş algılama ve şiddet ölçümü (Arduino Uno)
2// Knock detection and strength measurement with a piezo disc (Arduino Uno)
3const int PIEZO_PIN = A0; // piezo + 1 MΩ paralel / piezo with 1 MΩ in parallel
4const int LED_PIN = 13; // dahili LED / onboard LED
5const int ESIK = 40; // vuruş eşiği (0-1023) / knock threshold (0-1023)
6const int TEPE_PENCERE = 5; // tepe arama süresi, ms / peak search time, ms
7const int OLU_SURE = 80; // yankıyı yok sayma süresi, ms / time to ignore ringing, ms
8
9void setup() {
10 Serial.begin(115200);
11 pinMode(LED_PIN, OUTPUT);
12}
13
14void loop() {
15 int deger = analogRead(PIEZO_PIN);
16 if (deger < ESIK) return; // vuruş yok / no knock
17
18 // Eşik aşıldı: kısa pencerede en yüksek değeri bul / threshold crossed: find the peak in a short window
19 int tepe = deger;
20 unsigned long bas = millis();
21 while (millis() - bas < TEPE_PENCERE) {
22 int d = analogRead(PIEZO_PIN);
23 if (d > tepe) tepe = d;
24 }
25
26 float volt = tepe * 5.0 / 1023.0;
27 const char* siddet = tepe < 150 ? "hafif / soft" : (tepe < 500 ? "orta / medium" : "sert / hard");
28 Serial.print("Vurus / Knock: ");
29 Serial.print(tepe);
30 Serial.print(" ");
31 Serial.print(volt, 2);
32 Serial.print(" V ");
33 Serial.println(siddet);
34
35 digitalWrite(LED_PIN, HIGH);
36 delay(OLU_SURE); // disk titreşimi sönsün / let the disc stop ringing
37 digitalWrite(LED_PIN, LOW);
38}
39The trick in the code is the peak search. The first sample that crosses the threshold lands on the rising edge of the knock and can be much smaller than the real peak. So once the threshold is crossed, we keep reading for 5 ms and take the highest value; the Uno reads about 45 samples in that time (each analogRead takes about 112 microseconds). The dead time that follows stops the disc's decaying oscillation from being counted as a second knock. If you want to smooth readings in a noisy environment, see the sensor data filtering methods, but for knock detection this peak capture method is more correct than a moving average because it never misses the peak.
Knock strength table
The values below are typical ranges for a 27 mm disc taped to a table, a 1 MΩ parallel resistor and an Arduino Uno. How the disc is mounted, how hard the surface is and how far the knock is from the disc can change the result several times over, so use the table as a starting point and measure on your own setup. If the value reaches 1023, the signal is being clipped; to tell hard knocks apart, lower the sensitivity by dropping the parallel resistor to 470 kΩ.
| Type of knock | analogRead (0–1023) | Approx. voltage | Label in the code |
|---|---|---|---|
| No touch, ambient noise | 0–5 | 0–0.02 V | Not detected |
| Footstep nearby, putting a glass on the table | 5–40 | 0.02–0.2 V | Below threshold |
| Light touch with a fingertip | 40–150 | 0.2–0.7 V | Soft |
| Normal knock with a knuckle | 150–500 | 0.7–2.4 V | Medium |
| Hard knock, hit with a pen | 500–1023 | 2.4–5 V (clipped) | Hard |
Secret knock lock
The most popular piezo project is a secret lock that opens when someone knocks a certain rhythm on the door. The code records the knock times and scales the intervals to 0–100 relative to the longest interval; that way it doesn't matter whether you knock fast or slow, only the ratio between knocks counts. If every interval is within 25 percent of the stored code, the lock opens. Hold the button on the KAYIT_BUTON pin while knocking and the new rhythm is saved as the code. The lock is a 12 V solenoid lock; since an Arduino pin can't drive a solenoid directly, connect D9 to the gate of a logic-level MOSFET such as the IRLZ44N and put a reverse 1N4007 diode across the solenoid. The new rhythm is lost when power is cut; to keep it, write it to EEPROM.
1// Gizli vuruş ritmiyle açılan kilit (Arduino Uno)
2// Lock that opens with a secret knock rhythm (Arduino Uno)
3const int PIEZO_PIN = A0;
4const int KILIT_PIN = 9; // MOSFET kapısı, solenoid kilit / MOSFET gate, solenoid lock
5const int YESIL_LED = 7; // doğru ritim / correct rhythm
6const int KIRMIZI_LED = 8; // yanlış ritim / wrong rhythm
7const int KAYIT_BUTON = 2; // basılı tutup vur: yeni ritim / hold and knock: new rhythm
8
9const int ESIK = 60; // vuruş eşiği / knock threshold
10const int OLU_SURE = 120; // tek vuruşun yankısı, ms / ringing of one knock, ms
11const unsigned long ZAMAN_ASIMI = 1500; // son vuruştan sonra bekleme, ms / wait after last knock, ms
12const int TOLERANS = 25; // her aralıkta izin verilen sapma, % / allowed error per interval, %
13const int MAKS_ARALIK = 9; // en fazla 10 vuruş / up to 10 knocks
14const unsigned long ACIK_SURE = 3000; // kilidin açık kalma süresi, ms / unlock time, ms
15
16// Aralıklar en uzun aralığa göre 0-100 ölçeğinde / intervals on a 0-100 scale of the longest one
17int sifre[MAKS_ARALIK] = {50, 25, 25, 50, 100, 50}; // 7 vuruşluk ritim / 7-knock rhythm
18int sifreAdet = 6; // aralık sayısı / number of intervals
19
20bool vurusVar() {
21 return analogRead(PIEZO_PIN) >= ESIK;
22}
23
24// İlk vuruştan sonra ritmi dinler, aralık sayısını döndürür / listens after the first knock, returns interval count
25int ritimDinle(int araliklar[]) {
26 unsigned long son = millis();
27 int adet = 0;
28 delay(OLU_SURE);
29 while (millis() - son < ZAMAN_ASIMI && adet < MAKS_ARALIK) {
30 if (vurusVar()) {
31 unsigned long simdi = millis();
32 araliklar[adet++] = simdi - son;
33 son = simdi;
34 delay(OLU_SURE);
35 }
36 }
37 // Hıza bağımlı olmamak için ölçekle / scale so the tempo does not matter
38 int enUzun = 1;
39 for (int i = 0; i < adet; i++) if (araliklar[i] > enUzun) enUzun = araliklar[i];
40 for (int i = 0; i < adet; i++) araliklar[i] = (long)araliklar[i] * 100 / enUzun;
41 return adet;
42}
43
44bool ritimDogru(const int araliklar[], int adet) {
45 if (adet != sifreAdet) return false;
46 for (int i = 0; i < adet; i++) {
47 if (abs(araliklar[i] - sifre[i]) > TOLERANS) return false;
48 }
49 return true;
50}
51
52void yanSon(int pin, int kez) {
53 for (int i = 0; i < kez; i++) {
54 digitalWrite(pin, HIGH); delay(150);
55 digitalWrite(pin, LOW); delay(150);
56 }
57}
58
59void setup() {
60 Serial.begin(115200);
61 pinMode(KILIT_PIN, OUTPUT);
62 pinMode(YESIL_LED, OUTPUT);
63 pinMode(KIRMIZI_LED, OUTPUT);
64 pinMode(KAYIT_BUTON, INPUT_PULLUP);
65}
66
67void loop() {
68 if (!vurusVar()) return;
69
70 int araliklar[MAKS_ARALIK];
71 int adet = ritimDinle(araliklar);
72
73 if (digitalRead(KAYIT_BUTON) == LOW) { // kayıt modu / record mode
74 if (adet > 0) {
75 for (int i = 0; i < adet; i++) sifre[i] = araliklar[i];
76 sifreAdet = adet;
77 Serial.print("Yeni ritim / new rhythm: ");
78 Serial.print(adet + 1);
79 Serial.println(" vurus / knocks");
80 yanSon(YESIL_LED, 2);
81 yanSon(KIRMIZI_LED, 2);
82 }
83 return;
84 }
85
86 if (ritimDogru(araliklar, adet)) {
87 Serial.println("Dogru ritim, kilit acik / correct rhythm, unlocked");
88 digitalWrite(YESIL_LED, HIGH);
89 digitalWrite(KILIT_PIN, HIGH); // solenoid çeker / solenoid pulls
90 delay(ACIK_SURE);
91 digitalWrite(KILIT_PIN, LOW);
92 digitalWrite(YESIL_LED, LOW);
93 } else {
94 Serial.println("Yanlis ritim / wrong rhythm");
95 yanSon(KIRMIZI_LED, 3);
96 }
97}
98Drum pad: turning hit strength into MIDI
The piezo disc is the heart of an electronic drum: real drum pads have the same discs inside. The sketch below scans three pads on A0, A1 and A2, converts the peak value of each hit into a MIDI velocity from 1 to 127, and sends notes on channel 10, the General MIDI drum channel; 36 is the kick, 38 the snare and 42 the closed hi-hat. The Uno's USB doesn't show up as a MIDI device directly, so on the computer you use a serial-MIDI bridge such as Hairless MIDI; for direct USB-MIDI with an Arduino Leonardo or Pro Micro, see the Arduino MIDI controller article. Separate the pads with foam; pads glued to the same board trigger each other.
1// 3 piezo davul pedi: vuruş şiddetini MIDI nota hızına çevirir (Arduino Uno)
2// 3 piezo drum pads: turns hit strength into MIDI velocity (Arduino Uno)
3// Bilgisayarda seri-MIDI köprüsüyle (ör. Hairless MIDI), 115200 baud
4// On the computer with a serial-MIDI bridge (e.g. Hairless MIDI), 115200 baud
5const int PED_SAYISI = 3;
6const int PEDLER[PED_SAYISI] = {A0, A1, A2};
7const byte NOTALAR[PED_SAYISI] = {36, 38, 42}; // kick, trampet / snare, kapalı hi-hat / closed hi-hat
8const int ESIK = 30; // ped eşiği / pad threshold
9const int TAVAN = 900; // bu değer ve üstü = 127 / this value and above = 127
10const unsigned long TEPE_US = 3000; // tepe arama, mikrosaniye / peak search, microseconds
11const unsigned long OLU_SURE = 60; // aynı pedin tekrar tetiklenmemesi, ms / retrigger lockout, ms
12const byte MIDI_KANAL = 9; // 0'dan sayılır: 10. kanal davul / counted from 0: channel 10 = drums
13
14unsigned long sonVurus[PED_SAYISI];
15
16void midiGonder(byte komut, byte nota, byte hiz) {
17 Serial.write(komut);
18 Serial.write(nota);
19 Serial.write(hiz);
20}
21
22void setup() {
23 Serial.begin(115200);
24}
25
26void loop() {
27 for (int i = 0; i < PED_SAYISI; i++) {
28 if (millis() - sonVurus[i] < OLU_SURE) continue;
29 int d = analogRead(PEDLER[i]);
30 if (d < ESIK) continue;
31
32 int tepe = d;
33 unsigned long bas = micros();
34 while (micros() - bas < TEPE_US) {
35 int x = analogRead(PEDLER[i]);
36 if (x > tepe) tepe = x;
37 }
38
39 byte hiz = map(constrain(tepe, ESIK, TAVAN), ESIK, TAVAN, 1, 127); // MIDI velocity 1-127
40 midiGonder(0x90 | MIDI_KANAL, NOTALAR[i], hiz); // Note On
41 midiGonder(0x80 | MIDI_KANAL, NOTALAR[i], 0); // Note Off
42 sonVurus[i] = millis();
43 }
44}
45Piezo sensor vs buzzer: same disc, two different uses
| Use | Pin mode | Signal | Extra parts | Arduino function |
|---|---|---|---|---|
| Knock sensor | Analog input | Decaying voltage coming from the disc | 1 MΩ parallel + protection | analogRead() |
| Passive buzzer | Digital output | Square wave from the board to the disc | Optional 100 Ω series resistor | tone(pin, frequency) |
| Active buzzer (a different part) | Digital output | Steady voltage, the tone is generated inside | None | digitalWrite() |
The same 27 mm disc can be a sensor in one project and a sound source in another. As a buzzer, tone() sends a square wave to the disc and it is loudest close to its resonant frequency, around 4–4.6 kHz; at lower frequencies the sound gets noticeably quieter. An active buzzer with its own oscillator can't be used as a sensor because it has a driver circuit on its leads. The details of passive and active buzzers are in the what is a buzzer article. A piezo disc differs from the SW-420 vibration sensor, which only reports yes or no, by measuring strength, and from the KY-038 sound sensor, which listens to sound in the air, by reacting to vibration through direct contact.
Piezo sensor with ESP32
The ESP32's ADC is 12-bit (0–4095) and with 11 dB attenuation measures roughly 0–3.1 V. For the piezo sensor we use GPIO 34 on ADC1; it is input only and can be read while Wi-Fi is on. The ESP32 ADC is not linear near zero and usually reads anything below 0.1 V as 0, which is why we set the threshold in millivolts, at around 150 mV. analogReadMilliVolts() uses the chip's calibration data to return millivolts directly. For protection, always use a 3.3 V Zener or a Schottky diode to 3V3. If you want to combine this code with Wi-Fi to build a door sensor that sends a notification to your phone on every knock, add the method from the ESP32 Telegram bot article.
1// ESP32 + piezo disk: milivolt cinsinden vuruş ölçümü ve vuruş sayacı
2// ESP32 + piezo disc: knock measurement in millivolts and a knock counter
3const int PIEZO_PIN = 34; // ADC1, yalnız giriş / ADC1, input only
4const int LED_PIN = 2; // çoğu kartta dahili LED / onboard LED on most boards
5const int ESIK_MV = 150; // eşik, milivolt / threshold, millivolts
6const int TEPE_PENCERE = 5; // ms
7const int OLU_SURE = 80; // ms
8unsigned long sayac = 0;
9
10void setup() {
11 Serial.begin(115200);
12 pinMode(LED_PIN, OUTPUT);
13 analogReadResolution(12); // 0-4095
14 analogSetAttenuation(ADC_11db); // yaklaşık 0-3,1 V aralığı / about 0-3.1 V range
15}
16
17void loop() {
18 int mv = analogReadMilliVolts(PIEZO_PIN); // kalibre edilmiş okuma / calibrated reading
19 if (mv < ESIK_MV) return;
20
21 int tepe = mv;
22 unsigned long bas = millis();
23 while (millis() - bas < TEPE_PENCERE) {
24 int x = analogReadMilliVolts(PIEZO_PIN);
25 if (x > tepe) tepe = x;
26 }
27
28 sayac++;
29 Serial.printf("Vurus / Knock #%lu: %d mV\n", sayac, tepe);
30 digitalWrite(LED_PIN, HIGH);
31 delay(OLU_SURE);
32 digitalWrite(LED_PIN, LOW);
33}
34Piezo sensor with Raspberry Pi Pico (MicroPython)
The Raspberry Pi Pico's ADC is 12-bit, but MicroPython's read_u16() scales the value up to 0–65535. For the piezo we use GP26 (ADC0); GP27 and GP28 are analog inputs too. The Pico's ADC inputs must not exceed 3.3 V, so the same 1 MΩ, 10 kΩ and 3.3 V Zener setup applies here. The limits in the code match the same voltages as the Uno example (0.7 V and 2.4 V), so the same knock gets the same label on both boards. The MicroPython loop is slower than the Uno, but it still takes dozens of samples in the 5 ms window and catches the knock peak easily.
1# Raspberry Pi Pico + piezo disk: vuruş algılama ve şiddet (MicroPython)
2# Raspberry Pi Pico + piezo disc: knock detection and strength (MicroPython)
3from machine import ADC, Pin
4import time
5
6piezo = ADC(26) # GP26 = ADC0
7led = Pin(25, Pin.OUT) # Pico dahili LED; Pico W'da Pin("LED") / onboard LED; Pin("LED") on Pico W
8ESIK = 2500 # 0-65535 ölçeğinde yaklaşık 0,13 V / about 0.13 V on the 0-65535 scale
9TEPE_PENCERE_MS = 5
10OLU_SURE_MS = 80
11
12
13def siddet(tepe):
14 # 0,7 V ve 2,4 V sınırları Uno koduyla aynı / same 0.7 V and 2.4 V limits as the Uno code
15 if tepe < 14000:
16 return "hafif / soft"
17 if tepe < 47000:
18 return "orta / medium"
19 return "sert / hard"
20
21
22while True:
23 d = piezo.read_u16()
24 if d < ESIK:
25 continue
26 tepe = d
27 bas = time.ticks_ms()
28 while time.ticks_diff(time.ticks_ms(), bas) < TEPE_PENCERE_MS:
29 x = piezo.read_u16()
30 if x > tepe:
31 tepe = x
32 volt = tepe * 3.3 / 65535
33 print("Vurus / Knock:", tepe, "{:.2f} V".format(volt), siddet(tepe))
34 led.on()
35 time.sleep_ms(OLU_SURE_MS) # yankıyı yok say / ignore ringing
36 led.off()
37Piezo sensor project ideas
- Secret knock door or box lock: add a servo or solenoid to the code above to build a treasure box that opens with a rhythm.
- Electronic drum kit: 4–6 pads, MIDI and drum software on the computer make a real kit; for the sound side, also look at the Arduino piano project.
- Earthquake and shock logger: stick the disc to a wall or floor and log shock strength with a timestamp (Arduino earthquake alarm).
- Glass break or safe alarm: a disc stuck to a window triggers the alarm on a hard impact (Arduino alarm system).
- Reaction and hit game: who hits the pad fastest and hardest when the LED lights up; show the score on a display.
Common mistakes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Random values without touching | No 1 MΩ resistor, floating pin | Connect 1 MΩ across the disc's two leads |
| Two or three detections for one knock | The disc is ringing | Raise the dead time to 120–150 ms |
| Light knocks are not detected | Threshold too high or disc not stuck well to the surface | Lower the threshold, stick the disc firmly, use a bigger parallel resistor |
| Hard knocks always read 1023 | The signal is clipped | Drop the parallel resistor to 470 kΩ or move the disc away from the impact point |
| ESP32 reads small knocks as 0 | The ADC's dead zone near zero | Keep the threshold above 100–150 mV |
| Hitting one pad also plays another | Vibration travels through the base to the other disc | Separate the pads with foam, use a threshold per pad |
| ESP32/Pico pin got damaged | Connected without protection | Use a 10 kΩ series resistor and a 3.3 V Zener or Schottky |
If you want to try the piezo disc as a sound source or build games that react to knocks, the BlueGrays app has the buzzer basics, buzzer frequency, simple piano and sound reaction test projects with step-by-step circuit diagrams and code; adding the knock detection code from this article to those projects is quite easy.
Frequently asked questions
How does a piezo sensor work?
A piezo sensor is a piezoelectric ceramic disc that produces a voltage when it is bent or squeezed. When a knock flexes the disc, a short, two-way voltage appears between its leads. The Arduino reads this voltage on an analog pin to detect the knock and measure its strength.
Why is a 1 MΩ resistor connected to a piezo sensor?
The 1 MΩ parallel resistor bleeds off the charge on the disc and pulls the signal to zero; without it the analog pin floats and the readings wander. The resistor value also sets the sensitivity: a smaller resistor makes the sensor less sensitive but faster, a bigger one more sensitive but slower.
How many volts does a piezo disc produce?
A light touch can produce a few hundred millivolts and a hard knock tens of volts. Even though the current is tiny, that peak voltage can damage an analog input. That's why it should be limited with a 1 MΩ parallel resistor, a series resistor and a Zener or Schottky diode that suits the board's voltage.
Can a piezo buzzer be used as a sensor?
A passive piezo buzzer or a bare piezo disc can be used as a sensor, since both are the same piezoelectric element. An active buzzer with a built-in oscillator circuit won't work as a sensor. Buzzers in a housing are less sensitive than a bare disc.
What is the difference between a piezo sensor and a vibration sensor?
Vibration modules like the SW-420 only report with a digital signal whether there is vibration. A piezo disc produces an analog voltage that changes with the strength of the knock, so you can tell soft and hard knocks apart and build strength-sensitive projects like drum pads.
How do you connect a piezo sensor to an ESP32?
Connect the disc's red lead through a 10 kΩ series resistor to an ADC1 pin such as GPIO 34, and the black lead to GND. Add a 1 MΩ resistor and a 3.3 V Zener diode between the pin and GND. Because the ESP32 ADC doesn't read well below 0.1 V, choose a threshold around 150 mV.
Projects to build after reading this
See all projects
Using a Buzzer
Ever wondered how a doorbell or an alarm makes its sound? The Arduino makes a small buzzer beep at short intervals: beep, pause, beep, pause.

Frequency Setting with Buzzer
You control the sound of a buzzer with four buttons: one starts the sound, one silences it, and the other two make it higher or lower.

Simple Piano with Buzzer and Button
Build your own little piano with eight buttons. Each button is one note, from low to high: do, re, mi, fa, sol, la, ti and high do.

Arduino Reaction Time Test with Sound Cue: Measure Your Reflexes in Milliseconds (LCD + Buzzer + 3 LEDs)
How fast are your reflexes? Press the button: the red LED says get ready, the yellow LED says steady and a random wait of 1.5 to 3.5 seconds begins. The moment the green LED lights up and the buzzer beeps, press again; your reaction time appears on the I2C LCD in milliseconds, with your session best and average below it. Press before green and the screen shows TOO EARLY! with a losing sound. Hold the button for a new player, so everyone races the same wait order.

Smart Electronic Safe
A small safe for your valuables that opens with a code. You type your four-digit code on the keypad; if it is right, the servo motor opens the lock, the green light comes on and the screen shows the…

ESP32 Melody Playback with Buzzer
Playing a simple melody (Twinkle Twinkle Little Star) with a passive buzzer. We play notes with tone() and noTone() functions like in Arduino - ESP32 works with the same syntax as Arduino Core 3.0+. Passive buzzer must be used (active buzzer does not play melody).

ESP32 RFID Door Lock (RC522 + Servo + OLED + Buzzer + LED)
We build a smart door lock with an ESP32, an RC522 RFID module, an SG90 servo, an SSD1306 OLED display, an active buzzer and 2 LEDs. When a card is scanned, its UID is checked against the authorized cards defined in the code; if it matches, the servo unlocks (green LED + 2 short beeps) and locks again after 5 seconds. An unknown card lights the red LED, gives 3 quick beeps and shows its UID on the OLED.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

