TUTORIALS RoboticsArduino

How to Play With MiniQ 2WD Complete Robot Kit v2.0- Lesson 8 (Compass)

DFRobot Mar 23 2017 986

Key Points

1. Library Route

Open the serial monitor：

3. Value printed through serial monitor

4. The relationship between direction and value

From the image upon we can know that if we get 0, it is north, and if we get 90, it is east. And be careful of the sensor direction in the robot, the x axis is nor as the same as the headstock, so if you get 90, it is 90-90=0, or if you get 270, it is 270-90=180, thus you can know the direction of you headstock.

5. The directionof every axis

6. The direction when robot towards west

Tips:1.Cause the compass sensor gets the value through geomagnetism, so you’d better not put any magnet goods near the sensor. And if you feel the value had anything wrong, check the object around.2.And you must put your robot flatiy, or the value will be inaccuracy.

7 .Rotate your Smartphone

Code Analysis

Import the libraries：
#include <Wire.h>//add 2.0C library
#include <HMC5883L.h>//add hmc5883 library

Defines:
HMC5883L compass;// Store our compass as a variable.
Init HMC5883
compass = HMC5883L(); // Construct a new HMC5883 compass.
compass.SetScale(1.3);
compass.SetMeasurementMode(Measurement_Continuous);// Set the measurement mode to Continuous

Get the value
MagnetometerRaw raw = compass.ReadRawAxis();// Retrive the raw values from the compass
MagnetometerScaled scaled = compass.ReadScaledAxis();// Retrived the scaled values from the compass (scaled to the configured scale).

Deal with the value get (calculate the direction by the components of two axis)
float xHeading = atan2(scaled.YAxis, scaled.XAxis);
float yHeading = atan2(scaled.ZAxis, scaled.XAxis);
float zHeading = atan2(scaled.ZAxis, scaled.YAxis);

Deal with the value (invert the value into 0-2PI)

Change the value from radian into angle
float xDegrees = xHeading * 180/M_PI;
float yDegrees = yHeading * 180/M_PI;
float zDegrees = zHeading * 180/M_PI;

8. HMC5883