Chek out Tom Igoe's code....
/*
/*
Pulse_in
by Tom Igoe
Reads the values from a Memsic 2125 2-axis accelerometer.
In order to do so, uses a function called pulseIn, which reads
the width of a pulse on a pin.
Created 11 Feb. 2006
*/
int xPin = 2; // x-axis input
int yPin = 3; // y-axis input
int roll = 0; // x-axis tilt
int pitch = 0; // y-axis tilt
// Function prototypes:
int pulseIn(int whatPin, int desiredState);
void setup() {
beginSerial(9600);
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
printString("Starting\r\n");
}
void loop() {
roll = pulseIn(xPin, HIGH); // read pulsewidth on x axis
printString("got a roll\n");
pitch = pulseIn(yPin, HIGH); // read pulsewidth on y axis
printString("got a pitch\n");
printInteger(roll); // print x axis value
printString("\t"); // print a tab character
printInteger(pitch); // print y axis value
printString("\r\n"); // print return character and newline character
}
/////////////////////////////////////////
/*
pulseIn function. reads the width of a pulse on a pin.
Takes a pin number and the desired state, HIGH or LOW.
Watches for the pin to change from the non-desired state to
the desired state, then counts loops until the pin changes
back again.
*/
int pulseIn(int whatPin, int desiredState) {
int count = 0; // local counter
int finalCount = 0; // final number of loops the pulse takes
int pinState; // state of the pin you're watching
int lastState = desiredState; // place to store the previous state of the pin
int difference = 0;
while (finalCount <= 0) {
pinState = digitalRead(whatPin);
difference = pinState - lastState;
if ((difference > 0) &&(desiredState == HIGH)) {
// start counting pulses
count++;
}
if ((difference < 0) &&(desiredState == HIGH)) {
// stop counting pulses
finalCount = count;
count = 0;
}
if ((difference < 0) &&(desiredState == LOW)) {
// start counting pulses
count++;
}
if ((difference > 0) &&(desiredState == LOW)) {
// stop counting pulses
finalCount = count;
count = 0;
}
// save the state of the pin as the old state,
// so we can get a new state to compare it to:
lastState = pinState;
}
// you're done. Return the final count:
return finalCount;
}