Objective:
In this project, we will read tilt sensor  signal from GPIO port 20 (Pin 38) and control the status of LED. When Pin 38 get high voltage(True), we turn on LED , otherwise turn off LED. The input signal value(1 or 0) will be displayed to screen every 0.1 second.

If you don’t know what is GPIO layout, check our tutorial How to read Raspberry Pi i/o pin diagram (GPIO pin graph)

Parts:

1 pc Raspberry Pi  2/3/zero raspi
1 pc 8GB MicroSD memory card preinstalled Raspbian OS. 8gtf
1 pc LED Red_LED
1 pc Mercury tilt sensor mercury_tilt
1 pc 200 Ω resistance 220_resistor
1 pc breadboard BREADBOARD
1 pc GPIO breakout kit(optional) breakout

Prerequisite:

1)Raspbian should be upgraded to latest version in order to support RPI.GPIO module
Please run following commands in shell:

2)Enable I2C and SPI protocol
To enable the protocol, run shell command

sudo raspi-config

Then select Advance Options and enable I2C and SPI

You need to reboot to effect the configuration

Connect circuit components as per following graph:

gpio-tilt-sensor

Caution: Unlike Arduino board 5V input voltage, Raspberry GPIO pin accept only 3 Volt. Wrong voltage input might damage the Pi board. Please be very careful!

Write python code
You have two way to write python code:
Option 1)

Run following command in shell window:

sudo nano gpiosensor.py
then copy python code and paste the code into gpiosensor.py
Then Type Ctrl X and Yes to save the file. and press enter

Option 2)https://osoyoo.com/wp-admin/post.php?post=804&action=edit#
You can also download above python file from our server by typing following shell command:

sudo wget http://osoyoo.com/driver/gpiosensor.py

Finally, run following command in shell window:

sudo python gpiosensor.py

If you turn the sensor board into vertical position, the pi will turn on LED.  If you put the board  into horizon position, the LED will be off.

Video Demo: