Projects / ESP32 secret knock box

ESP32 secret knock box

Intermediate2.7 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. ESP32

    Wire the sensor

    S to GPIO27, middle pin to 3V3, minus to GND.

  2. ESP3259°

    Wire the servo

    Signal to GPIO18, red to VIN, brown to GND.

  3. ESP32

    Wire the buzzer

    GPIO23 and GND.

  4. ESP3259°

    Install the library

    ESP32Servo from the Library Manager.

  5. ESP3259°

    Upload the sketch

    The servo goes to the locked position.

  6. ESP32KY031

    Knock the default rhythm

    Knock, knock, pause, knock, knock, then wait.

  7. ESP32KY031

    Teach a new one

    Hold BOOT while you knock a new rhythm.

In short

How do you build an ESP32 secret knock box?

An ESP32 listens to a knock sensor and opens a small servo latch on a toy box when you tap a secret rhythm, with a way to teach it a new one. You need ESP32 DevKit V1, Knock sensor module (KY-031), SG90 Micro Servo, Active buzzer 5 V and Breadboard 830 Tie Points. It takes 7 steps and about 160 minutes.

Level
Intermediate
Time
About 160 min
Parts
5

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Knock sensor SESP32 GPIO27Pulses when knocked
Knock sensor middle pinESP32 3V3Power at 3.3 V
Knock sensor -ESP32 GNDCommon ground
Servo signal (orange)ESP32 GPIO18Latch control
Servo power (red)ESP32 VIN pin5 V from USB, fine for one small servo
Servo ground (brown)ESP32 GNDCommon ground
Buzzer +ESP32 GPIO23Feedback sound
Buzzer -ESP32 GNDGround

Code

The KY-031 is a simple vibration switch that closes briefly when it is tapped or knocked. The program counts each knock with an interrupt and notes the time, and ignores any second pulse within 120 milliseconds, which is just the switch bouncing. A pause of one and a half seconds ends the pattern, and the program works out the gaps between the knocks. The secret is stored as a list of gaps, and a new pattern matches if it has the same number of gaps and each is within 180 milliseconds of the stored one, which forgives a human not tapping perfectly. If you hold the BOOT button while tapping, the pattern is saved as the new secret instead. A match makes the servo swing the latch open for five seconds and then close it again, with two short beeps. A wrong pattern gives one long beep. This is a fun toy and a good lesson in timing, not a real lock: anyone can open the lid by hand.

Runs on a virtual ESP32 Dev Module in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

#include <ESP32Servo.h>

const int KNOCK = 27, SERVO_PIN = 18, BUZZER = 23, LEARN = 0;   // GPIO0 is the BOOT button
const int ACTIVE_LEVEL = LOW;                      // flip to HIGH if your module is the other way round

Servo latch;

const int MAX_KNOCKS = 12;
volatile unsigned long stamps[MAX_KNOCKS];
volatile int count = 0;

int secret[MAX_KNOCKS];                            // gaps between knocks in milliseconds
int secretLen = 4;
const int TOLERANCE = 180;                         // how far each gap may be out

void IRAM_ATTR onKnock() {
  unsigned long now = millis();
  if (count < MAX_KNOCKS && (count == 0 || now - stamps[count - 1] > 120)) {
    stamps[count++] = now;
  }
}

void beep(int ms) {
  digitalWrite(BUZZER, HIGH); delay(ms);
  digitalWrite(BUZZER, LOW);  delay(80);
}

void setup() {
  Serial.begin(115200);
  pinMode(KNOCK, INPUT_PULLUP);
  pinMode(BUZZER, OUTPUT);
  pinMode(LEARN, INPUT_PULLUP);
  latch.attach(SERVO_PIN, 500, 2400);
  latch.write(0);                                  // locked
  int defaults[] = {400, 400, 800, 400};           // knock, knock, pause, knock, knock
  for (int i = 0; i < 4; i++) secret[i] = defaults[i];
  attachInterrupt(digitalPinToInterrupt(KNOCK), onKnock, ACTIVE_LEVEL == LOW ? FALLING : RISING);
}

void loop() {
  noInterrupts();
  int n = count;
  unsigned long last = (n > 0) ? stamps[n - 1] : 0;
  interrupts();

  if (n > 0 && millis() - last > 1500) {           // a silence of 1.5 seconds ends the pattern
    int gaps[MAX_KNOCKS];
    noInterrupts();
    for (int i = 1; i < n; i++) gaps[i - 1] = (int)(stamps[i] - stamps[i - 1]);
    count = 0;
    interrupts();
    int g = n - 1;

    if (digitalRead(LEARN) == LOW && g >= 2) {     // BOOT held: teach a new rhythm
      for (int i = 0; i < g; i++) secret[i] = gaps[i];
      secretLen = g;
      beep(100); beep(100);
      Serial.println("New rhythm saved");
    } else {
      bool ok = (g == secretLen);
      for (int i = 0; ok && i < g; i++) if (abs(gaps[i] - secret[i]) > TOLERANCE) ok = false;
      if (ok) {
        beep(100); beep(100);
        latch.write(90);                           // open
        delay(5000);
        latch.write(0);                            // lock again
      } else {
        beep(600);
      }
    }
  }
  delay(10);
}

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Knock the right rhythmTwo beeps and the latch opens
Wrong rhythmOne long beep
After five secondsThe latch closes again
Hold BOOT and knock a new rhythmTwo beeps, saved
Knock the new rhythmOpens

If it does not work

Knocks are not seen

Check S is on GPIO27 and try ACTIVE_LEVEL set to HIGH.

Too many knocks counted

Fix the sensor firmly to the box, and raise the 120 millisecond limit.

Right rhythm is refused

Raise the TOLERANCE, for example to 250.

Servo twitches or the board resets

Power the servo from a separate 5 V supply with the grounds joined.

Does not compile

Install the ESP32Servo library.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the ESP32 secret knock box?

ESP32 DevKit V1, Knock sensor module (KY-031), SG90 Micro Servo, Active buzzer 5 V and Breadboard 830 Tie Points.

How long does the ESP32 secret knock box take to build?

About 160 minutes for a intermediate maker, in 7 steps.

How do I know the ESP32 secret knock box works?

Knock the right rhythm: Two beeps and the latch opens. Wrong rhythm: One long beep. After five seconds: The latch closes again.

Knocks are not seen: what should I check?

Check S is on GPIO27 and try ACTIVE_LEVEL set to HIGH.

Too many knocks counted: what should I check?

Fix the sensor firmly to the box, and raise the 120 millisecond limit.

Right rhythm is refused: what should I check?

Raise the TOLERANCE, for example to 250.

Servo twitches or the board resets: what should I check?

Power the servo from a separate 5 V supply with the grounds joined.