121 |
pfowler |
1 |
#include <Wire.h>
|
|
|
2 |
|
|
|
3 |
int compassAddress = 0x42 >> 1; // From datasheet compass address is 0x42
|
|
|
4 |
// shift the address 1 bit right, the Wire library only needs the 7
|
|
|
5 |
// most significant bits for the address
|
|
|
6 |
int reading = 0;
|
|
|
7 |
|
|
|
8 |
void setup()
|
|
|
9 |
{
|
|
|
10 |
Wire.begin(); // join i2c bus (address optional for master)
|
|
|
11 |
Serial.begin(9600); // start serial communication at 9600bps
|
|
|
12 |
pinMode(13, OUTPUT);
|
|
|
13 |
digitalWrite(13, HIGH);
|
|
|
14 |
}
|
|
|
15 |
|
|
|
16 |
void loop()
|
|
|
17 |
{
|
|
|
18 |
// step 1: instruct sensor to read echoes
|
|
|
19 |
Wire.beginTransmission(compassAddress); // transmit to device
|
|
|
20 |
// the address specified in the datasheet is 66 (0x42)
|
|
|
21 |
// but i2c adressing uses the high 7 bits so it's 33
|
|
|
22 |
Wire.write('A'); // command sensor to measure angle
|
|
|
23 |
Wire.endTransmission(); // stop transmitting
|
|
|
24 |
|
|
|
25 |
// step 2: wait for readings to happen
|
|
|
26 |
delay(10); // datasheet suggests at least 6000 microseconds
|
|
|
27 |
|
|
|
28 |
// step 3: request reading from sensor
|
|
|
29 |
Wire.requestFrom(compassAddress, 2); // request 2 bytes from slave device #33
|
|
|
30 |
|
|
|
31 |
// step 4: receive reading from sensor
|
|
|
32 |
if (2 <= Wire.available()) // if two bytes were received
|
|
|
33 |
{
|
|
|
34 |
reading = Wire.read(); // receive high byte (overwrites previous reading)
|
|
|
35 |
reading = reading << 8; // shift high byte to be high 8 bits
|
|
|
36 |
reading += Wire.read(); // receive low byte as lower 8 bits
|
|
|
37 |
reading /= 10;
|
|
|
38 |
Serial.println(reading); // print the reading
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
delay(500); // wait for half a second
|
|
|
42 |
}
|