Tilt-a-Whirl Hookup Guide

This Tutorial is Retired!

This tutorial covers concepts or technologies that are no longer current. It's still here for you to read and enjoy, but may not be as useful as our newest tutorials.

Contributors: Toni_K
Favorited Favorite 1

Talking to the Sensor

Now that the hardware is hooked up and ready to go, we need to upload code to the Arduino in order to start communicating with the sensor.

You can download the example Arduino sketch here. The most up-to-date code is also available on GitHub. Feel free to take this code, and modify it for your own purposes and projects!

At the beginning of the sketch, both S1 and S2 are initialized as integers, connected to pins D2 and D3 respectively.

int tilt_s1 = 2;
int tilt_s2 = 3;

This would be where you would initialize any additional sensors you would like to connect to the Arduino. Each additional pin would need to be defined as an integer and would need to be assigned to a digital pin that is still available.

Moving on to the set up loop, pins D2 and D3 are set as inputs, and serial communication is initialized at 9600 bps.

void setup()
    pinMode(tilt_s1, INPUT);
    pinMode(tilt_s2, INPUT);

Keep in mind, if you add in additional sensors, you will need to define the pinMode for each additional sensor pin as an input. You can also change the serial communication speed if necessary for your particular application.

Within the function loop, we simply use two functions. First, the function getTiltPosition() is called, which digitally reads the input from the two sensor pins. The received data is then processed using bitwise math, and returned to the main loop.

int getTiltPosition()
    int s1 = digitalRead(tilt_s1);
    int s2 = digitalRead(tilt_s2);
    return (s1 << 1) | s2; //bitwise math to combine the values

The function loop then assigns the data to the variable 'position', which is then printed out over the serial connection.

void loop()
    int position = getTiltPosition();
    delay(200); //only here to slow down the serial output

The sensor data will then be displayed every 2 milliseconds on the serial display.

That's it! It really is that simple to get communication with your sensor started.