Blame | Last modification | View Log | RSS feed
#include <Wire.h>int compassAddress = 0x42 >> 1; // From datasheet compass address is 0x42// shift the address 1 bit right, the Wire library only needs the 7// most significant bits for the addressint reading = 0;void setup(){Wire.begin(); // join i2c bus (address optional for master)Serial.begin(9600); // start serial communication at 9600bpspinMode(13, OUTPUT);digitalWrite(13, HIGH);}void loop(){// step 1: instruct sensor to read echoesWire.beginTransmission(compassAddress); // transmit to device// the address specified in the datasheet is 66 (0x42)// but i2c adressing uses the high 7 bits so it's 33Wire.write('A'); // command sensor to measure angleWire.endTransmission(); // stop transmitting// step 2: wait for readings to happendelay(10); // datasheet suggests at least 6000 microseconds// step 3: request reading from sensorWire.requestFrom(compassAddress, 2); // request 2 bytes from slave device #33// step 4: receive reading from sensorif (2 <= Wire.available()) // if two bytes were received{reading = Wire.read(); // receive high byte (overwrites previous reading)reading = reading << 8; // shift high byte to be high 8 bitsreading += Wire.read(); // receive low byte as lower 8 bitsreading /= 10;Serial.println(reading); // print the reading}delay(500); // wait for half a second}