Home 37 Sensor Kit KY-020 Tilt Switch Module arduino example

KY-020 Tilt Switch Module arduino example

by shedboy71

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

 

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

 

 

You may also like