Skip to content
Arduino contents

Lesson 1.2: Tilt sensor

A tilt sensor is a switch operated by gravity. It's the simplest way for a project to know whether it's upright, lying down or moving.

Parts

How it works

Inside the tube there are one or two metal balls. With the sensor upright they rest on both contacts and close the circuit; tilted past a certain angle, they roll away and open it.

To the Arduino it's exactly a push button: a switch between a pin and GND. With INPUT_PULLUP the pin reads HIGH when the circuit is open and LOW when it's closed, with no external resistors.

The balls bounce as they move, so the reading flickers for a few milliseconds on every change. A short pause between readings is enough to settle it.

Wiring

ComponentConnects toNote
Tilt sensor, leg 1Pin 2
Tilt sensor, leg 2GND
LED, anode (long leg)Pin 8Through the 220 Ω resistor
LED, cathode (short leg)GND

Code

// Lights the LED while the sensor is upright.
const int TILT_PIN = 2;
const int LED_PIN = 8;

void setup() {
  pinMode(TILT_PIN, INPUT_PULLUP); // internal resistor to 5 V
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  // Contacts closed: the pin is tied to GND and reads LOW.
  bool upright = digitalRead(TILT_PIN) == LOW;

  digitalWrite(LED_PIN, upright ? HIGH : LOW);
  delay(20); // let the ball stop bouncing
}

What the code does

  • INPUT_PULLUP enables the internal resistor that pulls the pin to 5 V. Without it, with the circuit open, the pin would float and read noise.
  • The logic is inverted: LOW means the contacts are closed.
  • The ? : operator picks HIGH or LOW in a single line; it's the same as an if / else.

Step by step

  1. Build the sensor and the LED on the breadboard following the table.
  2. Upload the code.
  3. Hold the sensor upright, legs pointing down: the LED lights up.
  4. Tilt it gradually and notice at what angle it goes out.

Result

The LED follows the sensor's position: on when upright, off when tilted or tipped over.

If it doesn't work

  • If it works the opposite way, it's the orientation: the ball closes the circuit with the legs pointing down.
  • If the LED never lights, check its polarity: the long leg goes towards the pin.
  • If it flickers when you move the sensor, lengthen the pause at the end of loop().