A tilt switch is designed to operate based on its orientation. They can operate a circuit based on whether they are tilted or not.
There are several types of tilt switches including; mercury switches, ball in cage switches among others. These switches have many applications such as in robotics, video game controllers, aircraft flight controls among others. This project makes use of the tilt ball switch.

Tilt Switch connection
One of the terminals is connected to Arduino digital pin to read the digital status as 1 or 0. The other terminal is connected to ground.

To show the state of the switch, we connect two leds, a blue one and a red one. When the switch is tilted and we're reading a 0, we turn on the red led. When the switch is at the normal position, the blue led is on. Below is the Arduino sketch.


// The tilt switch is connected to digital pin 2 of arduino the LEDs are connected to pin 4 and 6
int tiltSwitch = 7;
int tiltVal;
int redLed = 4;
int blueLed = 6;


void setup() {
  // The tilt switch is an input while the LEDs are outputs
  pinMode(tiltSwitch, INPUT);
  pinMode(redLed, OUTPUT);
  pinMode(blueLed, OUTPUT);

  // Make the switch on by default
  digitalWrite(tiltSwitch, HIGH);
}

void loop() {
  // Read the position by reading the tilt switch value. If tilted the value should be 0 (LOW)
  tiltVal = digitalRead(tiltSwitch);

  if (tiltVal == 0) {
    digitalWrite(redLed, HIGH);
    digitalWrite(blueLed, LOW);
  }

  if (tiltVal == 1) {
    digitalWrite(redLed, LOW);
    digitalWrite(blueLed, HIGH);
  }
}