Home Code Connect a tilt switch

Connect a tilt switch

by shedboy71

In this example we connect a tilt switch up to Pin 2 and connect an LED to pin 3, when we move the tilt switch the LED will light

 

Code


const int tiltPin = 2; // the number of the pushbutton pin
const int ledPin = 3; // the number of the LED pin
int tiltState = 0; // variable for reading the tilt switch status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the tilt switch pin as an input:
pinMode(tiltPin, INPUT);
}

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

// check if the tilt switch is pressed.
if (tiltState == HIGH)
{
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else
{
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

Share

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More