X
Home > Blog > STEM for ESP32 > Alarm! HOW to Use Tilt Sensor Against Theft with ESP32

Alarm! HOW to Use Tilt Sensor Against Theft with ESP32

By r January 7th, 2025 183 views

1. Overview

The tilt sensor is adopted to the anti-theft alarm project.

When object (such as a door or a window) tilts or moves, the ball rolls due to gravity to trigger the switch, which in turn activates the alarm system, such as a buzzer or LED indicator.

With simple structure, convenient installation and adjustable sensitivity, it is suitable for anti-theft alarm in home, office and shop doors, which effectively improves the security defence capability to detect and prevent potential intrusions in time.

2. Code Flow

a34

3. Wiring Diagram

b11

4. Test Code

/*  
  Project name: 16_Tilt_Alarm
  Function: Monitor whether the plane is tilted, if yes, red LED on and the buzzer alarms, if not, the green LED on and the buzzer does not sound
  Author: keyestudio    
  Hardware connection:  
    - Connect tilt senser to port 2
    - Connect traffic light module to port 9
    - Connect buzzer to port 3
  Library:  
    - none (no need to import additional library)  
  Cautions:  
    - Make sure you are connected to the correct interface   
    - Before uploading test code, please correctly connect to the development board and port
*/
#define tilt_Pin 2        //set button pin to IO2
#define beeppin 26        //Set pin to IO26
#define RED_LED_PIN 17    //Connect the red LED to port IO17
#define GREEN_LED_PIN 19  //Connect the green LED to port IO19

void setup() {
  //Set pin modes
  pinMode(tilt_Pin, INPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(beeppin, OUTPUT);  
  Serial.begin(9600);
}

void loop() {
  //Read TTL level of pin IO2 (high level '1', low level '0')
  int tilt_state = digitalRead(tilt_Pin);
  Serial.println(tilt_state);
  //Determine whether to tilt
  if (tilt_state == 1) {
    //If it tilts, the red LED on, the buzzer alerts
    digitalWrite(RED_LED_PIN, HIGH);
    digitalWrite(GREEN_LED_PIN, LOW);
    tone(beeppin,384);
    delay(500);

  } else {
    //If there is no tilt, the green LED on, the buzzer does not sound
    digitalWrite(RED_LED_PIN, LOW);
    digitalWrite(GREEN_LED_PIN, HIGH);
    noTone(beeppin);
  }
}

5. Test Result

After uploading the test code, when there is no tilt, the LED on the tilt sensor and the green LED turn on, and the sound sensor stays quiet. When tilt is detected, the LED on the tilt module is off, and the red LED is on, and the sound sensor emit sound.

Noise! HOW to Use Sound Sensor Control LEDwith ESP32
Previous
Noise! HOW to Use Sound Sensor Control LEDwith ESP32
Read More
Comprehension! HOW to Monitor Smart Home Environment with ESP32
Next
Comprehension! HOW to Monitor Smart Home Environment with ESP32
Read More
Message Us