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_BasicKit /04_tiltSwitch/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.

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;
}