Lesson 4 Tilt-Switch

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp


The tilt-switch we use here is a ball tilt-switch with a metal ball inside. It is used to detect small angle of inclination.


-1*Raspberry Pi

– 1*Network cable (or USB wireless network adapter)

– 1*Tilt-switch

– 1*Resistor (220Ω)

– 1*LED

– Several jumper wires

Experimental Principle

The principle is very simple. It mainly uses the ball in the switch changing with different angle of inclination to achieve the purpose of triggering circuits. When the ball in tilt switch runs from one end to the other end because of external force shaking, the tilt switch will conduct, or it will break.

In this experiment, we will use an LED and a tilt-switch to build a tilt indication light. When the tilt-switch is tilt, the LED will light up. Otherwise, it will go out.

Experimental Procedures

Step 1: Connect the circuit

Step 2: Edit and save the code (see path/Rpi_BasicKit /04_tiltSwitch/tiltSwitch.c)

Step 3: Compile the code      

gcc  tiltSwitch.c  -lwiringPi

Step 4: Run the program


Press Enter, if you tilt the switch, the LED will light up. Otherwise, it will go out.

C Code

#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <wiringPi.h> #define LedPin 0 #define TiltPin 1 int main(void) { if(wiringPiSetup() < 0){ fprintf(stderr, “Unable to setup wiringPi:%s\n”,strerror(errno)); return 1; } pinMode(TiltPin, INPUT); pinMode(LedPin, OUTPUT); pullUpDnControl(TiltPin, PUD_UP); while(1){ if(0 == digitalRead(TiltPin)){ digitalWrite(LedPin, LOW); } else{ digitalWrite(LedPin, HIGH); } } return 0; } 

Python Code

#!/usr/bin/env python import RPi.GPIO as GPIO LedPin = 11 # pin11 — led TiltPin = 12 # pin12 — button def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin’s mode is output GPIO.setup(TiltPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set Tilt Pin’s mode is input, and pull up to high level(3.3V) GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led def loop(): while True: if GPIO.input(TiltPin) == GPIO.LOW: print ‘…led on’ GPIO.output(LedPin, GPIO.LOW) # led on else: print ‘led off…’ GPIO.output(LedPin, GPIO.HIGH) # led off def destroy(): GPIO.output(LedPin, GPIO.HIGH) # led off GPIO.cleanup() # Release resource if __name__ == ‘__main__’: # Program start from here setup() try: loop() except KeyboardInterrupt: # When ‘Ctrl+C’ is pressed, the child program destroy() will be executed. destroy()