The HMC5883L is a digital compass module that utilizes a magnetometer to sense magnetic fields, allowing it to determine the Earth's magnetic headings. This small and low-cost module is commonly used in navigation systems for drones, robotics, and handheld compasses. Its ability to provide precise heading information makes it an essential component in orientation and position detection applications.
Pin Number | Name | Description |
---|---|---|
1 | VCC | Power supply (2.16V to 3.6V) |
2 | GND | Ground |
3 | SCL | Serial Clock Line for I2C |
4 | SDA | Serial Data Line for I2C |
5 | DRDY | Data Ready (optional, active low) |
To use the HMC5883L in a circuit:
#include <Wire.h>
// HMC5883L I2C address is 0x1E
#define Addr 0x1E
void setup() {
// Initialise I2C communication as MASTER
Wire.begin();
// Initialise serial communication, set baud rate = 9600
Serial.begin(9600);
// Configure the HMC5883L
Wire.beginTransmission(Addr);
// Select mode register
Wire.write(0x02);
// Continuous measurement mode
Wire.write(0x00);
Wire.endTransmission();
delay(300);
}
void loop() {
int data[6];
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select data register
Wire.write(0x03);
Wire.endTransmission();
// Request 6 bytes of data
Wire.requestFrom(Addr, 6);
// Read 6 bytes of data
// xMag msb, xMag lsb, zMag msb, zMag lsb, yMag msb, yMag lsb
if (Wire.available() == 6) {
data[0] = Wire.read() << 8;
data[0] |= Wire.read();
data[1] = Wire.read() << 8;
data[1] |= Wire.read();
data[2] = Wire.read() << 8;
data[2] |= Wire.read();
}
// Convert the data
int xMag = data[0];
int zMag = data[1];
int yMag = data[2];
// Output data to serial monitor
Serial.print("Magnetic field in X-Axis: ");
Serial.println(xMag);
Serial.print("Magnetic field in Z-Axis: ");
Serial.println(zMag);
Serial.print("Magnetic field in Y-Axis: ");
Serial.println(yMag);
delay(500);
}
Q: How do I calibrate the HMC5883L? A: Calibration typically involves rotating the compass in all three axes and using software to find the calibration constants.
Q: Can the HMC5883L work with 5V systems? A: Directly connecting to a 5V system may damage the module. Use a level shifter or voltage divider for compatibility with 5V systems.
Q: How can I check if the HMC5883L is functioning properly? A: Run the example code provided and check the serial monitor for changing magnetic field values as you rotate the sensor.
Q: What is the purpose of the DRDY pin? A: The DRDY pin is an optional feature that signals when new data is available for reading, which can be useful for power-saving strategies or synchronizing readings.
Remember to always consult the HMC5883L datasheet for the most detailed and specific information regarding the operation and specifications of the component.