working sample for GY271 - HMC5883L

main
Yik Teng Hie 5 years ago
parent 82edfe4de5
commit 415c72881d

@ -40,7 +40,7 @@ Description | SCL | SDA | Remark
---|---|---|---
Official | MTMS (GPIO14) | GPIO2 |
Try | GPIO0 | GPIO2 |
Try | GPIO5 | GPIO4 | Wire() Default for generic esp8266
generic esp8266 | GPIO5 | GPIO4 | Wire() Default for generic esp8266
+ The change Wire default, update begin(SDA, SCL)
```

@ -0,0 +1,143 @@
/*
HMC5883L.cpp - Class file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk)/ 2012 bildr.org (Arduino 1.0 compatible)
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
Datasheet for HMC5883L:
http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf
*/
#include <Arduino.h>
#include "HMC5883L.h"
HMC5883L::HMC5883L()
{
m_Scale = 1;
}
MagnetometerRaw HMC5883L::ReadRawAxis()
{
uint8_t* buffer = Read(DataRegisterBegin, 6);
MagnetometerRaw raw = MagnetometerRaw();
raw.XAxis = (buffer[0] << 8) | buffer[1];
raw.ZAxis = (buffer[2] << 8) | buffer[3];
raw.YAxis = (buffer[4] << 8) | buffer[5];
return raw;
}
MagnetometerScaled HMC5883L::ReadScaledAxis()
{
MagnetometerRaw raw = ReadRawAxis();
MagnetometerScaled scaled = MagnetometerScaled();
scaled.XAxis = raw.XAxis * m_Scale;
scaled.ZAxis = raw.ZAxis * m_Scale;
scaled.YAxis = raw.YAxis * m_Scale;
return scaled;
}
int HMC5883L::SetScale(float gauss)
{
uint8_t regValue = 0x00;
if(gauss == 0.88)
{
regValue = 0x00;
m_Scale = 0.73;
}
else if(gauss == 1.3)
{
regValue = 0x01;
m_Scale = 0.92;
}
else if(gauss == 1.9)
{
regValue = 0x02;
m_Scale = 1.22;
}
else if(gauss == 2.5)
{
regValue = 0x03;
m_Scale = 1.52;
}
else if(gauss == 4.0)
{
regValue = 0x04;
m_Scale = 2.27;
}
else if(gauss == 4.7)
{
regValue = 0x05;
m_Scale = 2.56;
}
else if(gauss == 5.6)
{
regValue = 0x06;
m_Scale = 3.03;
}
else if(gauss == 8.1)
{
regValue = 0x07;
m_Scale = 4.35;
}
else
return ErrorCode_1_Num;
// Setting is in the top 3 bits of the register.
regValue = regValue << 5;
Write(ConfigurationRegisterB, regValue);
}
int HMC5883L::SetMeasurementMode(uint8_t mode)
{
Write(ModeRegister, mode);
}
void HMC5883L::Write(int address, int data)
{
Wire.beginTransmission(HMC5883L_Address);
Wire.write(address);
Wire.write(data);
Wire.endTransmission();
}
uint8_t* HMC5883L::Read(int address, int length)
{
Wire.beginTransmission(HMC5883L_Address);
Wire.write(address);
Wire.endTransmission();
Wire.beginTransmission(HMC5883L_Address);
Wire.requestFrom(HMC5883L_Address, length);
uint8_t buffer[length];
if(Wire.available() == length)
{
for(uint8_t i = 0; i < length; i++)
{
buffer[i] = Wire.read();
}
}
Wire.endTransmission();
return buffer;
}
char* HMC5883L::GetErrorText(int errorCode)
{
if(ErrorCode_1_Num == 1)
return ErrorCode_1;
return "Error not defined.";
}

@ -0,0 +1,78 @@
/*
HMC5883L.h - Header file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk) / 2012 bildr.org (Arduino 1.0 compatible)
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
Datasheet for HMC5883L:
http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf
*/
#ifndef HMC5883L_h
#define HMC5883L_h
#include <Arduino.h>
#include <Wire.h>
#define HMC5883L_Address 0x1E
#define ConfigurationRegisterA 0x00
#define ConfigurationRegisterB 0x01
#define ModeRegister 0x02
#define DataRegisterBegin 0x03
#define Measurement_Continuous 0x00
#define Measurement_SingleShot 0x01
#define Measurement_Idle 0x03
#define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1"
#define ErrorCode_1_Num 1
struct MagnetometerScaled
{
float XAxis;
float YAxis;
float ZAxis;
};
struct MagnetometerRaw
{
int XAxis;
int YAxis;
int ZAxis;
};
class HMC5883L
{
public:
HMC5883L();
MagnetometerRaw ReadRawAxis();
MagnetometerScaled ReadScaledAxis();
int SetMeasurementMode(uint8_t mode);
int SetScale(float gauss);
char* GetErrorText(int errorCode);
protected:
void Write(int address, int byte);
uint8_t* Read(int address, int length);
private:
float m_Scale;
};
#endif

@ -0,0 +1,116 @@
/*
HMC5883L_Example.pde - Example sketch for integration with an HMC5883L triple axis magnetomerwe.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk)
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Reference the I2C Library
#include <Wire.h>
// Reference the HMC5883L Compass Library
#include <HMC5883L.h>
// Store our compass as a variable.
HMC5883L compass;
// Record any errors that may occur in the compass.
int error = 0;
// Out setup routine, here we will configure the microcontroller and compass.
void setup()
{
// Initialize the serial port.
Serial.begin(9600);
Serial.println("Starting the I2C interface.");
Wire.begin(); // Start the I2C interface.
Serial.println("Constructing new HMC5883L");
compass = HMC5883L(); // Construct a new HMC5883 compass.
Serial.println("Setting scale to +/- 1.3 Ga");
error = compass.SetScale(1.3); // Set the scale of the compass.
if(error != 0) // If there is an error, print it out.
Serial.println(compass.GetErrorText(error));
Serial.println("Setting measurement mode to continous.");
error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode to Continuous
if(error != 0) // If there is an error, print it out.
Serial.println(compass.GetErrorText(error));
}
// Our main program loop.
void loop()
{
// Retrive the raw values from the compass (not scaled).
MagnetometerRaw raw = compass.ReadRawAxis();
// Retrived the scaled values from the compass (scaled to the configured scale).
MagnetometerScaled scaled = compass.ReadScaledAxis();
// Values are accessed like so:
int MilliGauss_OnThe_XAxis = scaled.XAxis;// (or YAxis, or ZAxis)
// Calculate heading when the magnetometer is level, then correct for signs of axis.
float heading = atan2(scaled.YAxis, scaled.XAxis);
// Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the magnetic field in your location.
// Find yours here: http://www.magnetic-declination.com/
// Mine is: 2<> 37' W, which is 2.617 Degrees, or (which we need) 0.0456752665 radians, I will use 0.0457
// If you cannot find your Declination, comment out these two lines, your compass will be slightly off.
float declinationAngle = 0.0457;
heading += declinationAngle;
// Correct for when signs are reversed.
if(heading < 0)
heading += 2*PI;
// Check for wrap due to addition of declination.
if(heading > 2*PI)
heading -= 2*PI;
// Convert radians to degrees for readability.
float headingDegrees = heading * 180/M_PI;
// Output the data via the serial port.
Output(raw, scaled, heading, headingDegrees);
// Normally we would delay the application by 66ms to allow the loop
// to run at 15Hz (default bandwidth for the HMC5883L).
// However since we have a long serial out (104ms at 9600) we will let
// it run at its natural speed.
// delay(66);
}
// Output the data down the serial port.
void Output(MagnetometerRaw raw, MagnetometerScaled scaled, float heading, float headingDegrees)
{
Serial.print("Raw:\t");
Serial.print(raw.XAxis);
Serial.print(" ");
Serial.print(raw.YAxis);
Serial.print(" ");
Serial.print(raw.ZAxis);
Serial.print(" \tScaled:\t");
Serial.print(scaled.XAxis);
Serial.print(" ");
Serial.print(scaled.YAxis);
Serial.print(" ");
Serial.print(scaled.ZAxis);
Serial.print(" \tHeading:\t");
Serial.print(heading);
Serial.print(" Radians \t");
Serial.print(headingDegrees);
Serial.println(" Degrees \t");
}

@ -0,0 +1,31 @@
#######################################
# Syntax Coloring Map For Matrix
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
HMC5883L KEYWORD1
MagnetometerRaw KEYWORD1
MagnetometerScaled KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
ReadRawAxis KEYWORD2
ReadScaledAxis KEYWORD2
SetMeasurementMode KEYWORD2
SetScale KEYWORD2
XAxis KEYWORD2
YAxis KEYWORD2
ZAxis KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
Measurement_Continuous LITERAL1
Measurement_SingleShot LITERAL1

@ -1,77 +0,0 @@
#include "MechaQMC5883.h"
#include <Wire.h>
void MechaQMC5883::setAddress(uint8_t addr){
address = addr;
}
void MechaQMC5883::WriteReg(byte Reg,byte val){
Wire.beginTransmission(address); //start talking
Wire.write(Reg); // Tell the HMC5883 to Continuously Measure
Wire.write(val); // Set the Register
Wire.endTransmission();
}
void MechaQMC5883::init(){
WriteReg(0x0B,0x01);
//Define Set/Reset period
setMode(Mode_Continuous,ODR_200Hz,RNG_8G,OSR_512);
/*
Define
OSR = 512
Full Scale Range = 8G(Gauss)
ODR = 200HZ
set continuous measurement mode
*/
}
void MechaQMC5883::setMode(uint16_t mode,uint16_t odr,uint16_t rng,uint16_t osr){
WriteReg(0x09,mode|odr|rng|osr);
}
void MechaQMC5883::softReset(){
WriteReg(0x0A,0x80);
}
/**
* read values from device
* @return status value:
* - 0:success
* - 1:data too long to fit in transmit buffer
* - 2:received NACK on transmit of address
* - 3:received NACK on transmit of data
* - 4:other error
* - 8:overflow (magnetic field too strong)
*/
int MechaQMC5883::read(int* x,int* y,int* z){
Wire.beginTransmission(address);
Wire.write(0x00);
int err = Wire.endTransmission();
if (err) {return err;}
Wire.requestFrom(address, 7);
*x = (int)(int16_t)(Wire.read() | Wire.read() << 8);
*y = (int)(int16_t)(Wire.read() | Wire.read() << 8);
*z = (int)(int16_t)(Wire.read() | Wire.read() << 8);
byte overflow = Wire.read() & 0x02;
return overflow << 2;
}
int MechaQMC5883::read(int* x,int* y,int* z,int* a){
int err = read(x,y,z);
*a = azimuth(y,x);
return err;
}
int MechaQMC5883::read(int* x,int* y,int* z,float* a){
int err = read(x,y,z);
*a = azimuth(y,x);
return err;
}
float MechaQMC5883::azimuth(int *a, int *b){
float azimuth = atan2((int)*a,(int)*b) * 180.0/PI;
return azimuth < 0?360 + azimuth:azimuth;
}

@ -1,61 +0,0 @@
#ifndef Mecha_QMC5883
#define Mecha_QMC5883
#include "Arduino.h"
#include "Wire.h"
#define QMC5883_ADDR 0x0D
//REG CONTROL
//0x09
#define Mode_Standby 0b00000000
#define Mode_Continuous 0b00000001
#define ODR_10Hz 0b00000000
#define ODR_50Hz 0b00000100
#define ODR_100Hz 0b00001000
#define ODR_200Hz 0b00001100
#define RNG_2G 0b00000000
#define RNG_8G 0b00010000
#define OSR_512 0b00000000
#define OSR_256 0b01000000
#define OSR_128 0b10000000
#define OSR_64 0b11000000
class MechaQMC5883{
public:
void setAddress(uint8_t addr);
void init(); //init qmc5883
void setMode(uint16_t mode,uint16_t odr,uint16_t rng,uint16_t osr); // setting
void softReset(); //soft RESET
int read(int* x,int* y,int* z); //reading
int read(int* x,int* y,int* z,int* a);
int read(int* x,int* y,int* z,float* a);
float azimuth(int* a,int* b);
private:
void WriteReg(uint8_t Reg,uint8_t val);
uint8_t address = QMC5883_ADDR;
};
#endif

@ -1,138 +0,0 @@
# Mechasolution QMC5883L Library
[한글 설명 바로가기](https://github.com/keepworking/Mecha_QMC5883/blob/master/README_KO.md)
## Arduino Code
There are a few simple rules for using that library. Please read the following summary and apply it to your project
### Basic Elements
Required header files (#include ...) and Setup side code.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
void setup(){
Wire.begin();
}
```
### Object Declaration
The object declaration method. It is used outside the setup statement, and a name such as qmc can be changed to any other name you want.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
```
### initialization
QMC5883 Sensor's setting function.
The init function allows you to take advantage of the features of the QMC5883 sensor by default.
```cpp
void setup(){
Wire.begin();
qmc.init();
}
```
If you want more detailed settings, you can use it as follows.
```cpp
void setup(){
Wire.begin();
qmc.init();
qmc.setMode(Mode_Standby,ODR_200Hz,RNG_8G,OSR_512);
}
```
The values used for setMode can take the following values:
```
Mode : Mode_Standby / Mode_Continuous
ODR : ODR_10Hz / ODR_50Hz / ODR_100Hz / ODR_200Hz
ouput data update rate
RNG : RNG_2G / RNG_8G
magneticfield measurement range
OSR : OSR_512 / OSR_256 / OSR_128 / OSR_64
over sampling rate
```
### Read values
How to read the measured sensor value is as follows.
```cpp
void loop(){
int x,y,z;
qmc.read(&x,&y,&z);
}
```
and we can get azimuth too.
```cpp
void loop(){
int x,y,z;
int a;
//float a; //can get float value
qmc.read(&x,&y,&z,&a);
}
```
also can claculate azimuth you want
```cpp
void loop(){
int x,y,z;
int a;
qmc.read(&x,&y,&z);
a = qmc.azimuth(&y,&x);
}
```
## Basic example
It can be seen as a collection of the contents mentioned above.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
void setup() {
Wire.begin();
Serial.begin(9600);
qmc.init();
//qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}
void loop() {
int x,y,z;
qmc.read(&x,&y,&z);
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.print(z);
Serial.println();
delay(100);
}
```

@ -1,138 +0,0 @@
# Mechasolution QMC5883 Library
HMC5883 지자기 나침반 센서의 수명 만료(EOL)로인해 그동안의 HMC5883 센서는 생산이 중단 되었고, 대체 상품인 QMC5883으로 변경이 되었습니다.
## Arduino Code
해당 라이브러리를 이용하기 위한 몇가지 간단한 규칙이 있습니다. 아래 정리된 내용을 읽어주시고 사용하시는 프로젝트에 적용해 주세요
### 기본 요소
필수적으로 필요한 헤더파일(#include...)과 Setup 쪽 코드 입니다.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
void setup(){
Wire.begin();
}
```
### 객체 선언
객체 선언 방식입니다. setup문 밖에서 사용이 되며 qmc와 같은 이름은 사용자가 원하는 다른 이름으로 변경이 가능합니다.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
```
### 사용 설정
QMC5883 센서의 설정 함수 입니다.
init 함수를 사용하면 기본 설정으로 QMC5883센서의 기능을 이용할 수 있습니다.
```cpp
void setup(){
Wire.begin();
qmc.init();
}
```
좀더 세세한 설정을 원한다면 다음과 같이 사용이 가능합니다.
```cpp
void setup(){
Wire.begin();
qmc.init();
qmc.setMode(Mode_Standby,ODR_200Hz,RNG_8G,OSR_512);
}
```
setMode에 사용되는 값들은 다음 값들을 이용할 수 있습니다.
```
Mode : Mode_Standby / Mode_Continuous
ODR : ODR_10Hz / ODR_50Hz / ODR_100Hz / ODR_200Hz
ouput data update rate
RNG : RNG_2G / RNG_8G
magneticfield measurement range
OSR : OSR_512 / OSR_256 / OSR_128 / OSR_64
over sampling rate
```
### 값 읽기
측정한 센서의 값을 읽는 법은 다음과 같습니다.
```cpp
void loop(){
int x,y,z;
qmc.read(&x,&y,&z);
}
```
방위각에 대한 값입니다.
```cpp
void loop(){
int x,y,z;
int a;
//float a; //float 형도 지원됩니다.
qmc.read(&x,&y,&z,&a);
}
```
별도로 원하는 방위각도 구할 수 있습니다.
```cpp
void loop(){
int x,y,z;
int a;
qmc.read(&x,&y,&z);
a = qmc.azimuth(&y,&x);
}
```
### 기본 예제
다음은 라이브러리 기본 예제인 raw입니다.
위에 소개된 내용의 총집합으로 볼 수 있습니다.
```cpp
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
void setup() {
Wire.begin();
Serial.begin(9600);
qmc.init();
//qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}
void loop() {
int x,y,z;
qmc.read(&x,&y,&z);
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.print(z);
Serial.println();
delay(100);
}
```

@ -1,29 +0,0 @@
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
void setup() {
Wire.begin();
Serial.begin(9600);
qmc.init();
//qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}
void loop() {
int x, y, z;
int azimuth;
//float azimuth; //is supporting float too
qmc.read(&x, &y, &z,&azimuth);
//azimuth = qmc.azimuth(&y,&x);//you can get custom azimuth
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.print(z);
Serial.print(" a: ");
Serial.print(azimuth);
Serial.println();
delay(100);
}

@ -1,25 +0,0 @@
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
void setup() {
Wire.begin();
Serial.begin(9600);
qmc.init();
//qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}
void loop() {
int x,y,z;
qmc.read(&x,&y,&z);
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.print(z);
Serial.println();
delay(100);
}

@ -1,53 +0,0 @@
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The HMC5883
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking
Wire.write(0x0B); // Tell the HMC5883 to Continuously Measure
Wire.write(0x01); // Set the Register
Wire.endTransmission();
Wire.beginTransmission(addr); //start talking
Wire.write(0x09); // Tell the HMC5883 to Continuously Measure
Wire.write(0x1D); // Set the Register
Wire.endTransmission();
}
void loop() {
int x, y, z; //triple axis data
//Tell the HMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); //start with register 3.
Wire.endTransmission();
//Read the data.. 2 bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 6);
if (6 <= Wire.available()) {
x = Wire.read(); //MSB x
x |= Wire.read() << 8; //LSB x
z = Wire.read(); //MSB z
z |= Wire.read() << 8; //LSB z
y = Wire.read(); //MSB y
y |= Wire.read() << 8; //LSB y
}
// Show Values
Serial.print("X Value: ");
Serial.println(x);
Serial.print("Y Value: ");
Serial.println(y);
Serial.print("Z Value: ");
Serial.println(z);
Serial.println();
delay(500);
}

@ -1,25 +0,0 @@
#include <Wire.h>
#include <MechaQMC5883.h>
MechaQMC5883 qmc;
void setup() {
Wire.begin();
Serial.begin(9600);
qmc.init();
//qmc.setMode(Mode_Continuous,ODR_200Hz,RNG_2G,OSR_256);
}
void loop() {
int x,y,z;
qmc.read(&x,&y,&z);
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.print(z);
Serial.println();
delay(100);
}
Loading…
Cancel
Save