Tilt switch on an Arduino Uno
A ball tilt switch on pin 2 with the internal pull-up: tip it over and the LED on pin 13 lights, with the ball’s bounce filtered out. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner Runs in your browser. Free, and no account needed.
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Tilt switch: a ball in a tube that closes a contact while it stands up.
//
// pin 2 one leg of the tilt switch, the other leg to GND
// pin 13 the LED, through 220 ohm to GND
//
// Standing upright, the ball rests on the two contacts and joins them, so pin
// 2 is pulled to ground and reads LOW. Tip it over and the ball rolls away,
// the contact opens, and the internal pull-up brings the pin back HIGH. The
// LED lights while the switch is tipped.
//
// A rolling ball bounces on the contacts for a few milliseconds, so the sketch
// only believes a new state once it has held for 50 ms.
const int TILT = 2;
const int LED = 13;
const unsigned long SETTLE_MS = 50;
int stable = LOW;
int last = LOW;
unsigned long changedAt = 0;
void setup() {
pinMode(TILT, INPUT_PULLUP);
pinMode(LED, OUTPUT);
Serial.begin(9600);
Serial.println("Mokxi Uno: tilt switch");
stable = digitalRead(TILT);
last = stable;
}
void loop() {
int now = digitalRead(TILT);
if (now != last) {
last = now;
changedAt = millis();
}
if (now != stable && millis() - changedAt >= SETTLE_MS) {
stable = now;
digitalWrite(LED, stable == HIGH ? HIGH : LOW);
Serial.println(stable == HIGH ? "tipped over" : "upright");
}
}
Parts list
5 parts, plus the jumper wires. Every one is in the editor's parts bin.
- 1 × Arduino Uno R3
- 1 × Half breadboard
- 1 × Tilt switch
- 1 × Resistor, 220 Ω
- 1 × LED, red
How it is wired
4 connections, pin by pin, read from the circuit itself. Each line is one set of pins joined together, by a jumper wire or a breadboard strip.
- Ground: Arduino Uno R3 pin GND; Tilt switch pin 1; LED, red pin C
- Arduino Uno R3 pin 13; Resistor, 220 Ω pin 1
- Arduino Uno R3 pin 2; Tilt switch pin 2
- Resistor, 220 Ω pin 2; LED, red pin A
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.