Tilt alarm
A tilt switch detects when something is tipped over and sounds a buzzer.
Input · Beginner
In a real product: Anti-theft alarm (Smart home): Detects when something is moved or tipped.
A tilt switch closes when it is tipped past an angle (classic ones have a little ball that rolls onto two contacts). This module gives a clean HIGH while tilted, which is enough for a simple anti-theft or "knocked over" alarm.
What you'll learn
- Reading a digital sensor module
- Sounding a warning with a buzzer
- Reporting only changes, not every loop
How it works
The module's OUT goes to pin 2, with VCC and GND for power. OUT is HIGH while tilted.
While tilted, the loop lights the built-in LED and beeps the buzzer on pin 8 with tone(8, 1000, 100). It prints a message only when the state changes, so the Serial Monitor isn't flooded.
Try this
- Click the tilt switch while it runs to tip it.
- Latch the alarm: once tripped, keep beeping until a button resets it.
- Count how many times it was tilted.
sketch.ino
// A tilt switch module on pin 2 (HIGH while tilted) sounds a buzzer on pin 8.
const int TILT = 2;
const int BUZZER = 8;
bool wasTilted = false;
void setup() {
pinMode(TILT, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
bool tilted = digitalRead(TILT) == HIGH;
digitalWrite(LED_BUILTIN, tilted);
if (tilted) tone(BUZZER, 1000, 100);
if (tilted != wasTilted) {
wasTilted = tilted;
Serial.println(tilted ? "Tilted! Alarm" : "Level again");
}
delay(150);
}