6. Tilt Sensor

The tilt sensor is a component that can detect the tilting of an object. It is the equivalent to a pushbutton activated through a different physical mechanism. It contains a metallic ball inside that will alternate the two pins of the device from on to off and vice versa if the sensor reaches a certain angle (~90°).

6.1. Circuit

6.1.1. Simple Tilt-Activated LED

The image below depicts one way of connecting a tilt sensor. Simply connect it in series with an LED, resistor and battery, and then try to Tilt the sensor to turn on and off.

../_images/tilt-nopi.jpg ../_images/tiltsensor-principle.jpg

6.1.2. Connecting to Raspberry Pi

../_images/tiltsensor.jpg

6.2. Code Example

The code below will print out ‘1’ when the Sensor is placed on the board (initial position) and it will still return this result while the Sensor has not exceeded the Tilting threshold (LED ON in the previous example) and ‘0’ when it is tilted ~90° to any side (LED OFF):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)

while True:
        Tilt = GPIO.input(7) #tilt is '0' or '1'
        print Tilt
        time.sleep(1)