Hardware Reference
In-Depth Information
If the sketch is in calibrating
mode, it calls the compass calibrate()
method continuously. If not, it reads
the compass and reports the heading.
Then it waits 100 milliseconds to let
the compass stabilize before reading
again.
8
// if you're in calibration mode, calibrate:
if (calibrating) {
compass.calibrate();
}
else { // if in normal mode, read the heading:
compass.read();
int heading = compass.heading();
Serial.println("Heading: " + String(heading) + " degrees");
}
delay(100);
}
When you run this sketch, open the
Serial Monitor, and then put the
compass in calibrating mode by
pressing the button. Turn it around 360
degrees on a level surface for a second
or two, then rotate it through all three
axes for a few seconds. Next, press
the button to put it in normal mode,
and you'll see the heading values. Zero
degrees should be due north, 180
degrees is due south, 90 degrees is
east, and 270 degrees is west.
Introducing the I2C Interface
The LSM303DLH compass uses a form of synchronous
serial communication called Inter-Integrated Circuit , or I2C .
Sometimes called Two-Wire Interface , or TWI , it's the other
common synchronous serial protocol besides SPI, which you
learned about in Chapter 4.
Unlike SPI, I2C devices don't need a chip select pin. Each
has a unique address, and the master device starts each
exchange by sending the address of the device with which it
wants to communicate.
+5V
RX
CTS
RTS
NC
NC
I2C connections have just two connections between the
controlling device (or master device) and the peripheral
device (or slave), as follows:
I2C is comparable to SPI, in that it uses a single clock on the
master device to coordinate the devices that are communi-
cating. Every I2C device uses two wires to send and receive
data: a serial clock pin, called the SCL pin, that the micro-
controller pulses at a regular interval; and a serial data pin,
called the SDA pin, over which data is transmitted. For each
serial clock pulse, a bit of data is sent or received. When the
clock changes from low to high (known as the rising edge
of the clock), a bit of data is transferred from the microcon-
troller to the I2C device. When the clock changes from high
to low (known as the falling edge of the clock), a bit of data
is transferred from the I2C device to the microcontroller.
Clock (SCK): The pin that the master pulses regularly.
Data (SDA): The pin that data is sent on, in both directions.
All devices on an I2C bus can share the same two lines.
The Arduino Wire library is the interface for I2C. On most
Arduino boards, the SDA pin is analog input pin 4, and the
SCL pin is on analog input pin 5. On the Arduino Mega, SDA
is digital pin 20 and SCL is 21.
Search WWH ::




Custom Search