Tilt Sensor Arduino: SW-520D Tilt Switch Wiring and Debounce
Tilt sensor Arduino guide: SW-520D ball tilt switch, pull-up wiring, bounce and debounce, angle table, tip-over alarm, shake toy, Uno, ESP32 and Pico code.
In tilt sensor Arduino projects, the cheapest and simplest option is the SW-520D tilt switch. This little cylinder has two metal balls inside: while the sensor stands upright, the balls bridge the two legs and the switch is closed; tilt it past a certain angle and the balls roll away from the contacts and the switch opens. So the SW-520D doesn't give you an angle; it only tells you "upright" or "tilted" as on and off, just like a push button. For tip-over alarms, shake-to-light toys and detecting whether something has been moved, that's usually all you need.
In this guide you'll look inside the SW-520D, get an approximate tilt angle and trigger table, and wire it with a pull-up to an Arduino Uno, an ESP32 and a Raspberry Pi Pico. We'll measure the bounce the balls create and clean it up with debounce; then we'll write a tip-over alarm, a shake-to-light toy, an ESP32 that wakes from deep sleep when tilted, and MicroPython code. The last part explains when you should move to a real accelerometer such as the MPU6050.
What is the SW-520D tilt switch and how does it work?
The SW-520D is a tilt switch that uses metal balls instead of mercury, which is why it safely replaces the old mercury switches. At the bottom of the cylinder there are two contacts connected to the two legs. When you hold it upright with the legs pointing down, gravity pushes the balls to the bottom and the two contacts are joined through the balls: the switch is closed. Tip the sensor over and the balls roll towards the wall of the cylinder, the connection breaks and the switch opens. Both legs are identical; there is no plus or minus. The switch itself uses no power; the only current is what flows through the pull-up resistor you use to read it while it's upright: about 0.1–0.25 mA with the Uno's internal pull-up at 5 V.
| Feature | SW-520D |
|---|---|
| Type | Ball tilt switch, mercury-free |
| Output | Open / closed (digital), no angle value |
| Upright | Closed (both legs connected) |
| Tilted or upside down | Open |
| Legs | 2, non-polarised |
| Current limit | Signal level; don't drive an LED, motor or relay directly |
| Own consumption | None; 0.1–0.25 mA through the internal pull-up at 5 V when upright |
| Similar parts | SW-200D, SW-460D (different angle and size), KY-020 module |
Tilt angle and trigger table
The SW-520D's trigger angle is not a sharp limit: how the balls roll depends on friction, vibration and small production differences from piece to piece. The table below sums up what you typically see as the sensor tilts away from vertical (legs down). To find your own sensor's angle, build the circuit, tilt the sensor slowly against a protractor or a spirit-level app on your phone, and note the angle at which the state changes in the Serial Monitor. If you need a sharper, repeatable threshold, use an accelerometer that gives you an angle value.
| Angle from vertical | Where the balls are | Read with pull-up | Note |
|---|---|---|---|
| 0–10° | At the bottom, touching both contacts | LOW (closed) | Stable |
| 10–30° | Still mostly in contact | Usually LOW | Short HIGH bounces when shaken |
| 30–60° | Transition zone, starting to roll | Changes between LOW and HIGH | Most parts open here; debounce is a must |
| 60–90° | Resting against the wall, no contact | HIGH (open) | Horizontal: stable open |
| 90–180° (upside down) | At the cap end | HIGH (open) | Stable |
Wiring: pull-up on Uno, ESP32 and Pico
| Connection | Arduino Uno / Nano | ESP32 | Raspberry Pi Pico | Note |
|---|---|---|---|---|
| SW-520D leg 1 | D2 | GPIO 33 | GP15 | Internal pull-up on |
| SW-520D leg 2 | GND | GND | GND | Non-polarised, either leg |
| Module VCC (KY-020, LM393 type) | 5V | 3V3 | 3V3 (OUT) | Only if you use a module |
| Module DO / S | D2 | GPIO 33 | GP15 | Output logic may be inverted on some modules |
| LED (with 220 Ω) | D13 (on-board) or D9 (PWM) | GPIO 2 | GP14 | Status indicator |
| Buzzer | D8 | - | - | For the tip-over alarm |
The easiest way to connect a bare SW-520D is to wire one leg to a digital pin and the other to GND and enable the pin's internal pull-up resistor. Then the pin is tied to GND and reads LOW while the sensor is upright; when it's tilted, the switch opens and the pull-up pulls the pin HIGH. The logic is the same as wiring a push button. Ready-made modules come in two kinds: simple ones like the KY-020 only carry the switch and a 10 kΩ resistor, while LM393-based ones add a comparator, a sensitivity potentiometer and a status LED and give a clean digital output. A module's output logic may be inverted; check the value in the Serial Monitor upright and tilted and adjust the code to match.
Bounce and debounce
As the balls touch and leave the contacts, a single tilt can make and break contact dozens of times within milliseconds. Because the Arduino reads thousands of times per second, it sees every one of these bounces as a separate event: one tilt shows up in a counter as 10–30 presses. The fix is debounce: every time the raw value changes, a timer restarts, and the value is only accepted as the real state once it has stayed the same for 50 ms. The code below prints both the raw edge count and the clean state, so you can tilt the sensor a few times and see for yourself how fast the raw count climbs.
1// SW-520D eğim anahtarı: pull-up ile okuma, sıçrama sayımı ve debounce
2// SW-520D tilt switch: reading with pull-up, bounce counting and debounce
3const int TILT_PIN = 2; // Anahtarın bir bacağı D2, diğeri GND / one leg to D2, the other to GND
4const int LED_PIN = 13; // Dahili LED: eğikken yanar / on-board LED: lights when tilted
5const unsigned long DEBOUNCE_MS = 50; // Bu süre boyunca değişmeyen değer kabul edilir / a value must stay this long
6
7int rawLast = LOW; // Son ham okuma / last raw reading
8int stableState = LOW; // Debounce sonrası durum / state after debounce
9unsigned long lastChange = 0;
10unsigned long rawEdges = 0; // Ham kenar sayısı (sıçramalar dahil) / raw edge count (bounces included)
11
12void setup() {
13 pinMode(TILT_PIN, INPUT_PULLUP); // Dik: anahtar kapalı = LOW, eğik: açık = HIGH / upright: closed = LOW, tilted: open = HIGH
14 pinMode(LED_PIN, OUTPUT);
15 Serial.begin(9600);
16 rawLast = stableState = digitalRead(TILT_PIN);
17}
18
19void loop() {
20 int raw = digitalRead(TILT_PIN);
21 if (raw != rawLast) { // Her değişimde zamanlayıcıyı sıfırla / restart the timer on every change
22 rawLast = raw;
23 lastChange = millis();
24 rawEdges++;
25 }
26
27 if (millis() - lastChange > DEBOUNCE_MS && raw != stableState) {
28 stableState = raw; // Değer 50 ms sabit kaldı: gerçek değişim / stable for 50 ms: a real change
29 digitalWrite(LED_PIN, stableState == HIGH ? HIGH : LOW);
30 Serial.print(stableState == HIGH ? F("EGIK / TILTED") : F("DIK / UPRIGHT"));
31 Serial.print(F(" ham kenar / raw edges: "));
32 Serial.println(rawEdges); // Tek eğmede kaç sıçrama olduğunu gör / see how many bounces one tilt makes
33 }
34}50 ms is short enough that you won't notice it, yet long enough for the ball bounces to die out. If the sensor sits somewhere that vibrates a lot (a washing machine, a vehicle), raise the time to 100–200 ms; then only tilts that really last are counted. Since the code uses millis(), loop() never blocks and you can keep reading other sensors.
Tip-over alarm
A tip-over alarm warns you when something that should stay upright falls over, such as a heater, an aquarium light, a pram or a shipping box. The code ignores short jolts: the alarm only starts if the switch stays open for 1 second without a break, and it latches, so the buzzer keeps sounding even if the device is put back upright. The alarm is silenced only when you press the button on D3 while the device is upright again. An active buzzer is connected to D8; a 2 Hz beep grabs attention better than a constant tone.
1// Devrilme alarmı: cihaz 1 saniyeden uzun eğik kalırsa buzzer çalar, butonla susturulur
2// Tip-over alarm: the buzzer sounds if the device stays tilted for over 1 second, a button silences it
3const int TILT_PIN = 2; // SW-520D, diğer bacak GND / other leg to GND
4const int BUZZER_PIN = 8; // Aktif buzzer + / active buzzer +
5const int RESET_PIN = 3; // Susturma butonu, diğer ucu GND / silence button, other leg to GND
6const int LED_PIN = 13;
7const unsigned long TILT_TIME_MS = 1000; // Bu süre boyunca eğik kalırsa alarm / alarm after this long tilted
8
9unsigned long tiltedSince = 0;
10bool wasTilted = false;
11bool alarm = false;
12
13void setup() {
14 pinMode(TILT_PIN, INPUT_PULLUP);
15 pinMode(RESET_PIN, INPUT_PULLUP);
16 pinMode(BUZZER_PIN, OUTPUT);
17 pinMode(LED_PIN, OUTPUT);
18 Serial.begin(9600);
19}
20
21void loop() {
22 bool tilted = digitalRead(TILT_PIN) == HIGH; // Açık anahtar = eğik / open switch = tilted
23
24 // Sıçramalar süreyi sıfırlar; ancak sürekli eğiklik alarmı tetikler
25 // Bounces restart the timer; only a continuous tilt triggers the alarm
26 if (tilted && !wasTilted) tiltedSince = millis();
27 wasTilted = tilted;
28 if (tilted && !alarm && millis() - tiltedSince >= TILT_TIME_MS) {
29 alarm = true; // Alarm kilitlenir: cihaz düzelse de çalmaya devam eder / alarm latches even if the device is set upright
30 Serial.println(F("DEVRILDI! / TIPPED OVER!"));
31 }
32
33 if (alarm) {
34 bool on = (millis() / 250) % 2; // 2 Hz kesik ses / 2 Hz beeping
35 digitalWrite(BUZZER_PIN, on);
36 digitalWrite(LED_PIN, on);
37 if (digitalRead(RESET_PIN) == LOW && !tilted) { // Yalnız dik durumdayken susturulur / silence only when upright
38 alarm = false;
39 digitalWrite(BUZZER_PIN, LOW);
40 digitalWrite(LED_PIN, LOW);
41 Serial.println(F("Alarm susturuldu / alarm silenced"));
42 }
43 }
44}Shake-to-light toy
This time the bounces are exactly what we want: as you shake the sensor, the balls keep making and breaking contact, and every edge adds an "energy" point. The energy is kept between 0 and 255 and becomes the LED brightness via PWM; when you stop shaking, it drops every 20 ms and fades out in about 5 seconds. On a very hard shake the passive buzzer makes a short, rising beep. The idea easily becomes a magic wand, a glowing ball or a "power meter" toy for kids. Requiring at least 5 ms between edges stops the same bounce from being counted twice.
1// Sallayınca yanan oyuncak: SW-520D kenarlarını sayar, sallama şiddetine göre LED parlar ve yavaşça söner
2// Shake-to-light toy: counts SW-520D edges, the LED glows with shake strength and fades slowly
3const int TILT_PIN = 2;
4const int LED_PIN = 9; // PWM pini, 220 Ω ile LED / PWM pin, LED with 220 Ω
5const int BUZZER_PIN = 8; // İsteğe bağlı pasif buzzer / optional passive buzzer
6
7int lastRaw;
8unsigned long lastEdge = 0;
9int energy = 0; // 0-255 arası "enerji" / "energy" from 0 to 255
10unsigned long lastFade = 0;
11
12void setup() {
13 pinMode(TILT_PIN, INPUT_PULLUP);
14 pinMode(LED_PIN, OUTPUT);
15 lastRaw = digitalRead(TILT_PIN);
16}
17
18void loop() {
19 int raw = digitalRead(TILT_PIN);
20 // Burada sıçramalar işimize yarar: her kenar bir sarsıntı, 5 ms'den sıkı kenarlar yok sayılır
21 // Here bounces help: every edge is a jolt, edges closer than 5 ms are ignored
22 if (raw != lastRaw && millis() - lastEdge > 5) {
23 lastRaw = raw;
24 lastEdge = millis();
25 energy = min(energy + 25, 255);
26 if (energy > 200) tone(BUZZER_PIN, 400 + energy * 4, 20); // Güçlü sallamada kısa ses / short beep on hard shakes
27 }
28
29 if (millis() - lastFade >= 20) { // Her 20 ms'de biraz söndür / fade a little every 20 ms
30 lastFade = millis();
31 if (energy > 0) energy--;
32 analogWrite(LED_PIN, energy);
33 }
34}ESP32: a device that wakes from deep sleep when tilted
Because the tilt switch draws no current, it's a great wake-up source for battery devices. While the ESP32 waits in deep sleep the switch stays closed; if someone knocks the device over or picks it up and tilts it, GPIO 33 goes HIGH and the ext0 wake-up turns the ESP32 on. When it wakes, the code blinks the LED, stores the wake count in RTC memory and goes back to sleep after waiting until the device is upright and still again. You could add a Wi-Fi notification to your phone at this point. ext0 only works with RTC pins (GPIO 0, 2, 4, 12–15, 25–27, 32–39); rtc_gpio_pullup_en() keeps the internal pull-up on during sleep. While upright, about 70 µA flows through the pull-up; for less, use an external 1 MΩ pull-up.
1// ESP32: eğilince derin uykudan uyanan devrilme bildirici (ext0 uyandırma, GPIO 33)
2// ESP32: tip-over notifier that wakes from deep sleep when tilted (ext0 wake-up, GPIO 33)
3#include "esp_sleep.h"
4#include "driver/rtc_io.h"
5
6const gpio_num_t TILT_GPIO = GPIO_NUM_33; // RTC pini olmalı / must be an RTC pin; diğer bacak GND / other leg to GND
7const int LED_PIN = 2;
8RTC_DATA_ATTR int wakeCount = 0; // Uykuda kaybolmayan sayaç / counter that survives deep sleep
9
10void goToSleep() {
11 // Uykuda da dahili pull-up açık kalsın / keep the internal pull-up on during sleep
12 rtc_gpio_pullup_en(TILT_GPIO);
13 rtc_gpio_pulldown_dis(TILT_GPIO);
14 esp_sleep_enable_ext0_wakeup(TILT_GPIO, 1); // HIGH (eğik) olunca uyan / wake when HIGH (tilted)
15 Serial.println(F("Uykuya geciyor / going to sleep"));
16 Serial.flush();
17 esp_deep_sleep_start();
18}
19
20void setup() {
21 Serial.begin(115200);
22 pinMode(LED_PIN, OUTPUT);
23 rtc_gpio_deinit(TILT_GPIO); // Pini uykudan sonra normal GPIO'ya döndür / return the pin to normal GPIO after sleep
24 pinMode(TILT_GPIO, INPUT_PULLUP);
25
26 if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_EXT0) {
27 wakeCount++;
28 Serial.printf("Egim algilandi / tilt detected, toplam / total: %d\n", wakeCount);
29 // Burada Wi-Fi ile bildirim gönderilebilir / a Wi-Fi notification could be sent here
30 for (int i = 0; i < 6; i++) { digitalWrite(LED_PIN, i % 2 == 0); delay(150); }
31 }
32
33 // Cihaz yeniden dik ve sakin olana kadar bekle (1 sn kesintisiz LOW)
34 // Wait until the device is upright and still again (1 s of continuous LOW)
35 unsigned long calmSince = millis();
36 while (millis() - calmSince < 1000) {
37 if (digitalRead(TILT_GPIO) == HIGH) calmSince = millis();
38 delay(10);
39 }
40 goToSleep();
41}
42
43void loop() {
44 // Buraya hiç gelinmez / never reached
45}MicroPython code for the Raspberry Pi Pico
On the Pico you build the same logic in a few lines of MicroPython. The sensor goes between GP15 and GND, and Pin.PULL_UP enables the internal resistor; the LED sits on GP14 with 220 Ω. For debounce the code keeps timestamps with time.ticks_ms() and ticks_diff(); use these instead of plain subtraction because they handle counter wrap-around correctly. It also keeps the edges of the last second in a list: more than 8 edges means the device is being shaken. Save the code as main.py with Thonny and the Pico runs it at every power-up.
1# Raspberry Pi Pico (MicroPython): SW-520D eğim anahtarı, debounce ve sallama sayacı
2# Raspberry Pi Pico (MicroPython): SW-520D tilt switch, debounce and shake counter
3from machine import Pin
4import time
5
6tilt = Pin(15, Pin.IN, Pin.PULL_UP) # SW-520D: GP15 ve GND / GP15 and GND
7led = Pin(14, Pin.OUT) # LED + 220 ohm: GP14 / LED + 220 ohm on GP14
8
9DEBOUNCE_MS = 50
10stable = tilt.value()
11last_raw = stable
12last_change = time.ticks_ms()
13edges = [] # Son 1 saniyedeki kenarlar / edges in the last second
14
15while True:
16 now = time.ticks_ms()
17 raw = tilt.value()
18 if raw != last_raw:
19 last_raw = raw
20 last_change = now
21 edges.append(now)
22
23 # Debounce: 50 ms sabit kalan değer gerçek durumdur / a value stable for 50 ms is the real state
24 if time.ticks_diff(now, last_change) > DEBOUNCE_MS and raw != stable:
25 stable = raw
26 led.value(stable) # Eğik (1) iken LED yanar / LED on when tilted (1)
27 print("EGIK / TILTED" if stable else "DIK / UPRIGHT")
28
29 # 1 saniyede 8'den fazla kenar = sallanıyor / more than 8 edges in 1 s = shaking
30 edges = [t for t in edges if time.ticks_diff(now, t) < 1000]
31 if len(edges) > 8:
32 print("SALLANIYOR / SHAKING:", len(edges))
33 edges = []
34 time.sleep_ms(2)When should you move to an MPU6050?
The SW-520D answers a single question: "Is it tilted?" If you want to know in which direction and by how many degrees it's tilted, or how fast it's turning, you need a sensor like the MPU6050 with a 3-axis accelerometer and gyroscope. The MPU6050 connects over I2C, lets you calculate an angle for each axis and you can set the threshold to any degree in software. On the other hand it costs more, draws a few milliamps all the time and needs a library, calibration and filtering in code. If you only want to detect vibration or knocks, a spring-based SW-420 vibration sensor is another option.
| Question | SW-520D is enough | MPU6050 needed |
|---|---|---|
| Has the device tipped over? | Yes | Not needed |
| Which way did it tilt? | No (with one sensor) | Yes, X and Y axes |
| By how many degrees? | No | Yes, sub-degree resolution |
| Setting the threshold angle | No, mechanical and approximate | Any degree in software |
| Waiting for months on a battery | Yes, it draws no current itself | Hard, a few mA all the time |
| Rotation speed, gestures, step counting | No | Yes (gyroscope + accelerometer) |
| Price and wiring | Very cheap, 2 wires | More expensive, I2C (4 wires) |

Project ideas
- Idea: A safety circuit that cuts the socket with a relay module when a heater or lamp tips over.
- Idea: An anti-theft alarm with ESP32 deep sleep that goes off when a bike or bag is moved.
- Idea: A timer that restarts when you flip it over like an hourglass; show the remaining time with LEDs.
- Idea: A simple direction sensor using two SW-520D switches mounted at different angles to tell front-back from left-right tilt.
- Idea: A "you've got mail" alert when the letterbox flap opens and tilts the sensor.
- Idea: An electronic die that shows a random number from 1 to 6 when you shake it.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Value changes randomly | No pull-up, floating pin | Use INPUT_PULLUP or add an external 10 kΩ resistor |
| One tilt adds 20 to the counter | Ball bounce | Apply a 50 ms debounce |
| Sensor never reacts | Wrong mounting; fitted horizontally | Mount it upright with the legs down; it should read LOW upright |
| Logic works backwards | LM393 module output is inverted | Swap the meaning of HIGH and LOW in the code |
| False alarms where it vibrates | Jolts cause short openings | Require 1–2 seconds of continuous tilt |
| ESP32 keeps waking up | Device stayed tilted, or a non-RTC pin was chosen | Wait until upright before sleeping, use an RTC pin (e.g. GPIO 33) |
| ESP32/Pico pin got hot or died | Module powered from 5V | On 3.3 V boards power the module from 3V3 |
The SW-520D tilt sensor works with two legs and an internal pull-up, which makes it one of the easiest sensors to learn and a great exercise for core skills such as reading buttons, debouncing and tracking state. If you want to see related projects step by step with circuit diagrams and ready-to-use code, from button-controlled LEDs to a debounce comparison and deep sleep, check out the Arduino, ESP32 and Raspberry Pi Pico projects in the BlueGrays app.
Frequently asked questions
How does a tilt sensor work?
Ball tilt sensors such as the SW-520D have metal balls inside a cylinder. While the sensor is upright, the balls bridge the two contacts and the switch is closed; tilted past a certain angle, the balls roll away and the switch opens. The result is open or closed like a push button, with no angle value.
At what angle does the SW-520D trigger?
There's no exact value; most parts open somewhere around 30–60 degrees from vertical and stay reliably open beyond 60 degrees and upside down. The angle varies with friction, vibration and from part to part. Measuring your own sensor with a protractor or a spirit-level app on your phone is the most reliable way.
How do I connect a tilt sensor to Arduino?
Connect one leg to a digital pin such as D2 and the other to GND, and use pinMode(2, INPUT_PULLUP) in the code. It reads LOW when upright and HIGH when tilted. No extra resistor is needed; with a module you connect VCC to 5V and DO to a digital pin.
Why does my tilt sensor keep switching on and off?
The balls inside bounce many times within milliseconds as they touch and leave the contacts, and the Arduino sees each bounce as a separate change. Debounce code that waits for the value to stay stable for 50 ms solves it. Without a pull-up the pin floats and reads random values, which looks like the same problem.
What's the difference between the SW-520D and the MPU6050?
The SW-520D only tells you tilted or upright, uses no current and works with two wires. The MPU6050 is a 3-axis accelerometer and gyroscope; it measures tilt direction, angle and rotation speed, connects over I2C and draws a few milliamps continuously. If you need an angle, use the MPU6050; to detect tipping over, the SW-520D is enough.
Can a tilt sensor be used with an ESP32 or Raspberry Pi Pico?
Yes. Connect a bare SW-520D between a GPIO and GND and enable the internal pull-up; the voltage doesn't matter. On an ESP32, wiring it to an RTC pin lets you wake the device from deep sleep with a tilt. If you use an LM393 module, power it from 3V3 on 3.3 V boards.
Projects to build after reading this
See all projects
LED Control with a Push Button (Push)
Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

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.

Raspberry Pi Pico Button Debounce: IRQ vs Software Polling
If one press of a button made your code count 3-4 times, the culprit is contact bounce: the button's metal contacts open and close many times within microseconds as they touch! In this project we count the same button in 2 different ways and compare them side by side in Serial: RAW polling (catches the bounce and miscounts) and IRQ + software debounce (counts correctly).

Raspberry Pi Pico Button Controlled LED (Push)
First input project with Pico — button read! LED lights while button is pressed, off when released. This is the big step after LED animations: signal input from the world to Pico. Learn Pin.IN (input mode), Pin.PULL_UP (internal pull-up resistor — standard for buttons), button.value() reading. GP14 LED, GP2 button (internal PULL_UP). Pressed = LOW (0), released = HIGH (1) — reverse logic seems confusing at first but is industry standard.

Reading a Reed Switch
Ever wondered about the magnetic switch inside door and window alarms? When a magnet comes near the reed relay module, the tiny switch inside it closes; the Arduino reads it once a second and prints…

Reed Switch Door Sensor
Tell whether your door is open or closed just by looking at a light. You attach a small magnet to the door and a magnet-sensing switch to the frame; when the door is closed they sit side by side and…

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.
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

