Lesson 14 Tilt Switch

Share for us

Introduction

The tilt switch sensor module is a ball tilt switch with a metal ball inside. It is used to detect inclinations of a small angle.

Components

– 1 * Raspberry Pi

– 1 * Breadboard

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

– 1 * Dual-color Common-Cathode LED module

– 1 * Tilt-switch module

– Several jumper wires

Experimental Principle

The principle is very simple: the ball in the tilt switch moves with different angles of inclination to make triggering circuits. When it tilts towards either side, as long as the tilt degree and force meet the condition, the switch will be energized; thus, it will output low level signals.

Experimental Procedures

Step 1: Build the circuit

Tilt-Switch                   Raspberry Pi

 S —————————— GPIO0

+ ——————————-  3.3V

 – ——————————–  GND

Dual-color LED module connection: connect pin R on dual-color LED module to GPIO1 on Raspberry Pi; GND to GND

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

Step 3: Compile

              gcc  tiltSwitch.c  -lwiringPi

Step 4: Run

              ./a.out

Tilt the switch and the state of LED will be switched ON/OFF.

tiltSwitch.c 

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>

#define  TiltPin     0
#define   LedPin     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);

	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

TiltPin = 11
LedPin  = 12

Led_status = 1

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)
	GPIO.output(LedPin, GPIO.LOW) # Set LedPin high(+3.3V) to off led

def swLed(ev=None):
	global Led_status
	Led_status = not Led_status
	GPIO.output(LedPin, Led_status)  # switch led status(on-->off; off-->on)
	print "LED: off" if Led_status else "LED: on"

def loop():
	GPIO.add_event_detect(TiltPin, GPIO.FALLING, callback=swLed, bouncetime=100) # wait for falling
	while True:
		pass   # Don't do anything

def destroy():
	GPIO.output(LedPin, GPIO.LOW)     # 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()