KY-020 Tilt Switch Module arduino example

The KY-020 Arduino tilt switch sensor module. The KY-020 is a metallic ball switch that will open/close the circuit depending on the angle its tilted at. It does not measure the angle.

KY-020 Tilt Switch Module
KY-020 Tilt Switch Module

What is a tilt switch?

A mercury switch is an electrical switch that opens and closes a circuit when a small amount of the liquid metal mercury connects metal electrodes to close the circuit. There are several different basic designs (tilt, displacement, radial, etc.) but they all share the common design strength of non-eroding switch contacts.

The most common is the mercury tilt switch. It is in one state (open or closed) when tilted one direction with respect to horizontal, and the other state when tilted the other direction. This is what older style thermostats used to turn a heater or air conditioner on or off.

Parts List

Name Link
Arduino Uno UNO R3 CH340G/ATmega328P, compatible for Arduino UNO
Sensor kit 37 IN 1 SENSOR KITS FOR ARDUINO HIGH-QUALITY FREE SHIPPING (Works with Official for Arduino Boards)
connecting wire Free shipping Dupont line 120pcs 20cm male to male + male to female and female to female jumper wire

 

Connection

This is the connections we used

Connect the module’s Power line (middle) and ground (-) to +5v and GND. Connect the signal pin (S) to pin 2 on the Arduino.

KY-020 module Arduino connection
S D2
middle +5V
GND
arduino and ky020 layout
arduino and ky020 layout

Code

We switch the on board LED on and off and also output text via the serial port

[codesyntax lang=”cpp”]

int tiltPin = 3;      // pin number for tilt switch 
int ledPin =  13;     // pin number of LED 
int tiltState = 0;

void setup() 
{ 
  Serial.begin(9600); 
  pinMode(ledPin, OUTPUT);  // set the LED pin as output      
  pinMode(tiltPin, INPUT);  // set the tilt switch pin as input
}

void loop()
{
  // read the tilt switch state
  tiltState = digitalRead(tiltPin);

  // check if the tilt switch is tilted.
  if (tiltState == HIGH) 
  {     
    digitalWrite(ledPin, HIGH);  
    Serial.println("switch is closed");
  } 
  else 
  {
    digitalWrite(ledPin, LOW); 
    Serial.println("switch is open");
  }
  delay(200);
}

[/codesyntax]

Output

Open the serial monitor and move the switch module

switch is closed
switch is closed
switch is closed
switch is closed
switch is open
switch is closed
switch is closed
switch is closed

 

 

This div height required for enabling the sticky sidebar
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :