# Sudden Motion Sensor on the Macbook

Dan Shiffman’s written a nice library to access the sudden motion sensor on the macbook and macbook pro. He based it on a couple other open source libraries. Below is a code sample for it that draws a plane on the screen and moves it as you tilt the computer.

```/*
smsTilt

Takes the values from the sudden motion sensor on a powerbook
(assuming the machine has the SMS in it: macBookPro, macBook, later Powerbooks)
and uses it to set the position, attitude, and color of a rectangle on the screen.

To use it, tilt your powerbook around.

created 28 October 2006
by Tom Igoe

*/

import sms.*;
int graphPosition = 0;                // horizontal position of the graph
int[] vals = new int[3];              // raw values from the sensor
int[] maximum = new int[3];           // maximum value sensed
int[] minimum = new int[3];           // minimum value sensed
int[] range = new int[3];             // total range sensed
float[] attitude = new float[3];      // current value as a attitude of window height
float[] position = new float[3];      // current value as a attitude of window height
float rectSize;                       // rectangle size

void setup () {
// draw the window:
size(400, 400, P3D);
// set the size of the rectangle:
rectSize = width/4;
// set the background color:
background(0);
// set the maximum and minimum values:
for (int i = 0; i < 3; i++) {
maximum[i] = 400;
minimum[i] = -400;
// calculate the total current range:
range[i] = maximum[i] - minimum[i];
}
}

void draw () {
background(0);
// get the values:
vals = Unimotion.getSMSArray();
// check to see if you have new peak values:
checkLimits();
// draw the plane:
tilt();

}
void checkLimits() {
for (int i = 0; i < 3; i++) {
// calculate the current attitude as a percentage of 2*PI,
// based on the current range:
attitude[i] = PI * float(vals[i] - minimum[i]) /float(range[i]) ;
}

// calculate the current position as a percentage of the window height,
// based on the current range:
position[0] = width * float(vals[0] - minimum[0]) /float(range[0]);
position[1] = height * float(vals[1] - minimum[1]) /float(range[1]) + minimum[1];
position[2] = height * float(vals[2] - minimum[2]) /float(range[2]);
}

void tilt() {
// position:
translate(position[0], position[2], position[1] );
// pi/2, 0, 0 is level plane
// X is front-to-back
rotateX(attitude[1]);
// Y is left-to-right
rotateY(attitude[0] + PI/2);
// Z is pivot
rotateZ(attitude[2]+PI/4);
// draw the rect:
fill(position[0],position[1],position[2]);
rect(-rectSize, -rectSize, rectSize*2, rectSize*2);
}
```