Mercury Tilt switch work with Raspberry Pi

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)


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 220 Ω resistance 220_resistor
1 pc breadboard BREADBOARD
1 pc GPIO breakout kit(optional) breakout


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

  • sudo apt-get update
  • sudo apt-get upgrade

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:


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
then copy python code and paste the code into
Then Type Ctrl X and Yes to save the file. and press enter

Option 2)
You can also download above python file from our server by typing following shell command:

sudo wget

Finally, run following command in shell window:

sudo python

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:

Posted in Raspberry Pi Project
2 comments on “Mercury Tilt switch work with Raspberry Pi
  1. greeny480 says:

    I just got a pi 3 b and I have the one from amozon it is preloaded with noobs I beleave is the programing site radpbain on this ? New and have no clue please help!

Leave a Reply

WordPress spam blocked by CleanTalk.