# 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;              // raw values from the sensor
int[] maximum = new int;           // maximum value sensed
int[] minimum = new int;           // minimum value sensed
int[] range = new int;             // total range sensed
float[] attitude = new float;      // current value as a attitude of window height
float[] position = new float;      // 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 = width * float(vals - minimum) /float(range);
position = height * float(vals - minimum) /float(range) + minimum;
position = height * float(vals - minimum) /float(range);
}

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