Wiring a Tilt Switch

I bought one of the Arduino Sidekick component kits from RadioShack this weekend and I’d like to build a few circuits with those parts over the next few posts. I’ll be using Mike Margolis’ Arduino Cookbook which is the best text on tinkering with Arduinos that I have found, and I highly recommend it.

First Part(s)

In the component pack there’s little baggies of jumper wires, resistors, capacitors, switches, LEDs, and then one special little baggie of DOO-DADS. In this little baggie is a tilt switch, diode, photo resistor, thermistor, buzzer, and potentiometer. I didn’t know at first which one was a tilt switch, so I’ll share that little bit of info in this handy DOO-DAD-O-DIAGRAM

You’ll note from the diagram that the tilt switch is longer and thicker than the diode. Also, if you shake it, you’ll hear a thingy rolling around in the body of the component. If you’re lucky, it should be the only thing in the baggie that rattles.

The only things you’ll need outside of the box of components is an Arduino, and a USB cord linking the Arduino to your computer. Within the box of components you’ll need two 1k Ohm resistors (brown-black-red), some jumper wires, and two LED lights, red and green. Below are two images I created with Fritzing.

The Sketch

After connecting the components as shown, I uploaded this sketch. This should turn the green LED on when the switch is tilted one way, and then turn the red LED on when it is tilted the other way.

/*
  tilt sensor
*/

const int TILTPIN =  2 ;
const int LEDPIN1 = 11 ;
const int LEDPIN2 = 12 ;

void setup()
{
  pinMode( TILTPIN, INPUT ) ;
  pinMode( LEDPIN1, OUTPUT ) ;
  pinMode( LEDPIN2, OUTPUT ) ;
  digitalWrite( TILTPIN, HIGH ) ;
}

void loop()
{
  if( digitalRead( TILTPIN ) ) 
  {
    digitalWrite( LEDPIN1, HIGH ) ; # Turn the red LED on
    digitalWrite( LEDPIN2, LOW )  ; # Turn the green LED off
  }
  else{
    digitalWrite( LEDPIN1, LOW )  ; # Turn the red LED off
    digitalWrite( LEDPIN2, HIGH ) ; # Turn the green LED on
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *