3-axis magnetometer HMC5883L and Arduino

The tutorial shows how to handle a digital magnetometer with an Arduino.

 

In this example we used the following elements:

 

Connect the sensor with Arduino:

The module communicates using the popular I2C bus. Thus, the connection to the Arduino needs to be done in the following way:

 

Module HMC5883L Pin Arduino
VCC 5 V
GND GND
SCL A5
Traffic A4

 

 

 

Wiring diagram of the magnetometer with Arduino Uno.

 

Program for Arduino

In the example, we used the following code:

 

  1. #include //I2C library
  2. #define address 0x1E //address module for I2C HMC5883L
  3. void setup(){
  4. Serial.begin(9600); //initialize serial communication
  5. Wire.begin(); //initialize the module
  6. //Configure the appropriate sensor mode
  7. Wire.beginTransmission(address); //open connection
  8. Wire.write(0x02); //select mode register
  9. Wire.write(0x00); //continuous measurement
  10. Wire.endTransmission();
  11. }
  12. void loop(){
  13. int x,y,z; //variables for the three axes
  14. //Setting the address to read data
  15. Wire.beginTransmission(address);
  16. Wire.write(0x03); //select register 3, the register MSB of X-axis
  17. Wire.endTransmission();
  18. //Read data for each axis, two entries on the same axle
  19. Wire.requestFrom(address, 6);
  20. if(6<=Wire.available()){
  21. x = Wire.read()<<8; //MSB of X-axis
  22. x |= Wire.read(); //LSB X axis
  23. with the = Wire.read()<<8; //MSB of axis
  24. s |= Wire.read(); //LSB axis
  25. y = Wire.read()<<8; //MSB of Y-axis
  26. y |= Wire.read(); //LSB Y axis
  27. }
  28. //Display data on serial monitor
  29. Serial.print("x: ");
  30. Serial.print(x);
  31. Serial.print(" y: ");
  32. Serial.print(y);
  33. Serial.print (": ");
  34. Serial.println ();
  35. delay(250); //delay between measurements 250 MS
  36. }

 

The results of the program can be seen below:

 

A screenshot of the serial monitor.

Botland.store - shop for makers!