Introduction
In this experiment, we will use the HMC5883L digital compass sensor to measure the magnetic field and determine the direction. This can be useful for navigation applications.
Components Needed
- HMC5883L Digital Compass Sensor
- Arduino (e.g., Uno, Nano)
- Jumper wires
- Breadboard
Circuit Setup
- Connect the VCC pin of the HMC5883L to the 3.3V pin of the Arduino.
- Connect the GND pin to the GND pin of the Arduino.
- Connect the SDA pin to A4 and the SCL pin to A5 on the Arduino (for I2C communication).
Ensure all connections are secure and check the orientation of the compass sensor.
Code for Digital Compass
Upload the following code to your Arduino to read the magnetic field and determine direction:
#include
#include
HMC5883L compass;
void setup() {
Serial.begin(9600);
Wire.begin();
compass.initialize();
}
void loop() {
Vector norm = compass.readNormalize();
float heading = atan2(norm.YAxis, norm.XAxis);
if (heading < 0) {
heading += 2 * M_PI;
}
float headingDegrees = heading * 180/M_PI;
Serial.println(headingDegrees);
delay(500);
}
Explanation
The HMC5883L uses I2C communication to send magnetic field data to the Arduino. The code processes this data to calculate the heading in degrees and displays it in the Serial Monitor.
Troubleshooting
- If the readings are inconsistent, check for magnetic interference around the sensor.
- Ensure correct wiring for I2C communication and confirm the compass is not placed near strong magnetic fields.