Hier ein Beispielcode:
[code]
#include <Wire.h> //I2C Arduino Library
#define addr 0x1E //I2C Address for The HMC5883
void setup(){
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking
Wire.write(0x02); // Set the Register / Das Register auswählen
Wire.write(0x00); // Tell the HMC5883 to Continuously Measure
Wire.endTransmission();
}
void loop(){
int x,y,z; // Daten der 3 Achsen
int s; // Status
char id, id1, id2; // Identification Register A, B, C
//Tell the HMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x03); //start with register 3.
Wire.endTransmission();
// Lesen der 3 Achsen, je 2x 8bit (3x 2 Register)
Wire.requestFrom(addr, 6); // Anfrage an Gerät (addr) für 6 bytes
if(6<=Wire.available()){
x = Wire.read()<<8; //MSB x
x |= Wire.read(); //LSB x
z = Wire.read()<<8; //MSB z
z |= Wire.read(); //LSB z
y = Wire.read()<<8; //MSB y
y |= Wire.read(); //LSB y
}
// Lesen von Status und IDs
Wire.beginTransmission(addr);
Wire.write(0x09); // Starten mit Register 9
Wire.endTransmission();
Wire.requestFrom(addr, 4);
if(4<=Wire.available()){
s = Wire.read();
id = Wire.read();
id1 = Wire.read();
id2 = Wire.read();
}
float heading = atan2(-y, x);
float declinationAngle = 39.85/1000;
heading += declinationAngle;
float headingDegrees = heading * RAD_TO_DEG;
if (headingDegrees < 0) headingDegrees += 360;
delay(100);
// Daten ausgeben
Serial.println("*****************************");
Serial.print("Kompass Grad: ");
Serial.println(headingDegrees);
Serial.print("X Value: ");
Serial.println(x);
Serial.print("Y Value: ");
Serial.println(y);
Serial.print("Z Value: ");
Serial.println(z);
Serial.println();
Serial.print("Status: ");
Serial.println(s, DEC);
Serial.println();
Serial.print("ID-A: ");
Serial.println(id);
Serial.print("ID-B: ");
Serial.println(id1);
Serial.print("ID-C: ");
Serial.println(id2);
Serial.println("*****************************");
delay(500);
}
[/code]
Keine Kommentare:
Kommentar veröffentlichen