HMC 5883 Example to return x y z values

include

include

include

Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345); // Create an instance of the HMC5883 sensor

void setup() { Serial.begin(9600); // Initialize the serial communication if (!mag.begin()) { Serial.println("No HMC5883 sensor detected!"); // Check if the HMC5883 sensor is detected while (1); } }

void loop() { sensors_event_t event; mag.getEvent(&event); // Get the magnetic field data from the sensor

float x = event.magnetic.x; // Get the X-axis magnetic field value float y = event.magnetic.y; // Get the Y-axis magnetic field value float z = event.magnetic.z; // Get the Z-axis magnetic field value

Serial.print("X: "); Serial.print(x); Serial.print(" Y: "); Serial.print(y); Serial.print(" Z: "); Serial.println(z);

delay(1000); // Delay for 1 second before reading the next set of values }

Explanation:

  1. Include necessary libraries: The code includes the required libraries for using the HMC5883 sensor and communicating with it via the I2C protocol.

  2. Create an instance of the HMC5883 sensor: An instance of the Adafruit_HMC5883_Unified class is created with a unique identifier (in this case, 12345).

  3. Setup function: The setup function is executed only once when the Arduino board is powered on or reset. It initializes the serial communication at a baud rate of 9600 and checks if the HMC5883 sensor is detected. If the sensor is not detected, the program enters an infinite loop, printing an error message.

  4. Loop function: The loop function is executed repeatedly after the setup function. It performs the main task of reading the magnetic field data from the sensor and printing the X, Y, and Z-axis values to the serial monitor.

  5. Get the magnetic field data: The mag.getEvent(&event) function retrieves the magnetic field data from the sensor and stores it in the "event" variable.

  6. Extract X, Y, and Z-axis values: The X, Y, and Z-axis magnetic field values are extracted from the event variable using event.magnetic.x, event.magnetic.y, and event.magnetic.z respectively.

  7. Print values to the serial monitor: The X, Y, and Z-axis values are printed to the serial monitor using the Serial.print and Serial.println functions.

  8. Delay: The delay(1000) function introduces a 1-second delay before reading the next set of magnetic field values. This helps in controlling the rate at which the values are printed to the serial monitor.