Lesson 4 Tilt Switch

Share for us

Introduction

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.

Components

– 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_UniversalStartKit /tiltSwitch.c)

Step 3: Compile the code

            gcc  tiltSwitch.c  -lwiringPi

Step 4: Run the program

            ./a.out

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

 tiltSwitch.c

#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
import time

LedPin  = 11    # pin11
TiltPin = 12

def setup():
	GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
	GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
	GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
	GPIO.setup(TiltPin, GPIO.IN)

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()