User Tools

Site Tools


oak:tutorials:rollingball

This is an old revision of the document!


Oak: Tilt Switching

This lesson will show you how to connect and use a Tilt switch to trigger the onboard LED. It will also demonstrate how to publish the fact that the switch has been tilted.

Components Used:

Part Quantity Identification
Oak with soldered headers 1
Breadboard 1
SW-520D Rolling Ball Switch 1
1k Resistor 1 Brown, Black, Red
M to M 30cm Jumper Wire 3 Red, Black, Blue

Concepts:

Tilt Switch: In this lesson we will be using a tilt switch to detect if the switch has been turned upside down. This will be achieved by reading the pin the tilt switch is connected to, much like a button.

A tilt switch

Pull-Down Resistor: In this lesson we will use a Pull-Down resistor to make sure we can reliably detect button presses. If an I/O pin is 'left floating' reading it's value can result in either HIGH or LOW. By attaching a resistor between the I/O pin of the Oak and GND we can ensure that if the button is not pressed, the state is always LOW.

Circuit:

You will want to insert the 10k resistor first. Make sure that the Red and Black wires go to the separate pins of the tilt switch and the blue goes to the same pin as the resistor, but on the tilt switch side of the resistor as in the diagram.

We will be using the onboard LED to display the state of the tilt switch.

Code:

// define which pins to use
const int tilt = 2;     // the number of the tilt switch pin
const int ledPin = 1;      // the number of the LED pin

// set a variable to record the switch's state
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(tilt, INPUT);
}

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

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

Conclusion:

oak/tutorials/rollingball.1460376639.txt.gz · Last modified: 2016/04/11 05:10 by nog3