2.1.5 Tilt Switch¶
Introduction¶
This is a ball tilt-switch with a metal ball inside. It is used to detect inclinations of a small angle.
Required Components¶
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
---|---|---|
Raphael Kit |
337 |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
---|---|
- |
Schematic Diagram¶
Experimental Procedures¶
Step 1: Build the circuit.
Step 2: Change directory.
cd ~/raphael-kit/c/2.1.5/
Step 3: Compile.
gcc 2.1.5_Tilt.c -lwiringPi
Step 4: Run.
sudo ./a.out
Place the tilt vertically, and the green LED will turns on. If you tilt it, “Tilt!” will be printed on the screen and the red LED will lights on. Place it vertically again, and the green LED will turns on again.
Note
If it does not work after running, or there is an error prompt: "wiringPi.h: No such file or directory", please refer to Install and Check the WiringPi.
Code
#include <wiringPi.h>
#include <stdio.h>
#define TiltPin 0
#define Gpin 2
#define Rpin 3
void LED(char* color)
{
pinMode(Gpin, OUTPUT);
pinMode(Rpin, OUTPUT);
if (color == "RED")
{
digitalWrite(Rpin, HIGH);
digitalWrite(Gpin, LOW);
}
else if (color == "GREEN")
{
digitalWrite(Rpin, LOW);
digitalWrite(Gpin, HIGH);
}
else
printf("LED Error");
}
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print message to screen
printf("setup wiringPi failed !");
return 1;
}
pinMode(TiltPin, INPUT);
LED("GREEN");
while(1){
if(0 == digitalRead(TiltPin)){
delay(10);
if(0 == digitalRead(TiltPin)){
LED("RED");
printf("Tilt!\n");
}
}
else if(1 == digitalRead(TiltPin)){
delay(10);
if(1 == digitalRead(TiltPin)){
LED("GREEN");
}
}
}
return 0;
}
Code Explanation
void LED(char* color)
{
pinMode(Gpin, OUTPUT);
pinMode(Rpin, OUTPUT);
if (color == "RED")
{
digitalWrite(Rpin, HIGH);
digitalWrite(Gpin, LOW);
}
else if (color == "GREEN")
{
digitalWrite(Rpin, LOW);
digitalWrite(Gpin, HIGH);
}
else
printf("LED Error");
}
Define a function LED()
to turn the two LEDs on or off. If the parameter
color is RED, the red LED lights up; similarly, if the parameter color
is GREEN, the green LED will turns on.
while(1){
if(0 == digitalRead(TiltPin)){
delay(10);
if(0 == digitalRead(TiltPin)){
LED("RED");
printf("Tilt!\n");
}
}
else if(1 == digitalRead(TiltPin)){
delay(10);
if(1 == digitalRead(TiltPin)){
LED("GREEN");
}
}
}
If the read value of tilt switch is 0, it means that the tilt switch is tilted then you write the parameter ”RED” into function LED to get the red LED lighten up; otherwise, the green LED will lit.