Hardware Reference
In-Depth Information
This sketch uses the Wire library to communicate via I2C
with the compass. The Wire library is encapsulated in
another library, the LSM303DLH library, originally written
by Ryan Mulligan of Pololu. I've made a variation on it with
a few extra functions, available at http://github.com/
tigoe/LSM303DLH. Download version 1.1.0 (the latest as
of this writing) and copy the LSM303DLH folder into the
libraries directory of your Arduino sketch directory. Note
that there is a folder called LSM303DLH inside the folder
you download. It's the inner folder that you want.
This sketch also uses Alexander Brevig's Button library;
the current Wiring version is at http://wiring.uniandes.
edu.co/source/trunk/wiring/firmware/libraries/Button ;
the current Arduino version is at http://github.com/tigoe/
Button . Download it to your libraries directory as well. Then,
restart Arduino and you're ready to begin.
X
Try It
There are no global
variables, but before the
setup() method, you have to include
the library and define a couple of
constants.
// include the necessary libraries:
#include <Wire.h>
#include <LSM303DLH.h>
#include <Button.h>
const int modeButton = 2; // pushbutton for calibration mode
const int buttonLed = 3; // LED for the button
// initialize the compass library
LSM303DLH compass;
// initialize a button on pin 2 :
Button button = Button(modeButton,BUTTON_PULLDOWN);
boolean calibrating = false; // keep track of calibration state
The setup() method initializes
the Wire and Serial libraries and
enables the compass.
8
void setup() {
// initialize serial:
Serial.begin(9600);
// set up the button LED:
pinMode(buttonLed,OUTPUT);
// start the Wire library and enable the compass:
Wire.begin();
compass.enable();
}
8
The main loop starts by checking
the button. If the button is currently
pressed and its state has changed
since the last check, the sketch toggles
between normal mode and calibrating
mode. It also changes the LED state:
on means you're calibrating, off means
normal mode.
void loop() {
// if the button changes state, change the calibration state
// and the state of the LED:
if(button.isPressed() && button.stateChanged()){
calibrating = !calibrating;
digitalWrite(buttonLed, calibrating);
}
 
Search WWH ::




Custom Search