The following is my code :
#include <Wire.h>
#define HMC5883_WriteAddress 0x1E // i.e 0x3C >> 1
#define HMC5883_ModeRegisterAddress 0x02
#define HMC5883_ContinuousModeCommand 0x00
#define HMC5883_DataOutputXMSBAddress 0x03
int outputData[6];
void setup()
{
//SerialUSB.begin(9600);
Wire.begin(); //Initiate the Wire library and join the I2C bus as a master
Wire.beginTransmission(HMC5883_WriteAddress); //Initiate a transmission with HMC5883 (Write address).
Wire.send(HMC5883_ModeRegisterAddress); //Place the Mode Register Address in send-buffer.
Wire.send(HMC5883_ContinuousModeCommand); //Place the command for Continuous operation Mode in send-buffer.
Wire.endTransmission(); //Send the send-buffer to HMC5883 and end the I2C transmission.
delay(1000);
}
void loop() {
int i,x,y,z;
Wire.beginTransmission(HMC5883_WriteAddress); //Initiate a transmission with HMC5883 (Write address).
Wire.send(HMC5883_DataOutputXMSBAddress); //select register 3, X MSB register
Wire.endTransmission();
Wire.requestFrom(HMC5883_WriteAddress,6); //Request 6 bytes of data from the address specified,2 registers per axis.
//Read the value of magnetic components X,Y and Z
if(6 <= Wire.available()) // If the number of bytes available for reading be <=6.
{
for(i=0;i<6;i++)
{
outputData[i]=Wire.receive(); //Store the data in outputData buffer
}
}
x=outputData[0] << 8 | outputData[1]; //Combine MSB and LSB of X Data output register
z=outputData[2] << 8 | outputData[3]; //Combine MSB and LSB of Z Data output register
y=outputData[4] << 8 | outputData[5]; //Combine MSB and LSB of Y Data output register
SerialUSB.print("X=");
SerialUSB.print(x);
SerialUSB.print(" Y=");
SerialUSB.print(y);
SerialUSB.print(" Z=");
SerialUSB.println(z);
delay(100);
}
But the result x y z is the same when i shake the HMC5883L-board.
Is anyone who have been use this IC before can tell me what's wrong with the code ,
thanks!