联合创作人招募中!
微信联系:yulone

HMC5883L 三轴磁力计 电子指南针使用教程

本文为爱鱼客原创内容,未经作者及本站允许请勿转载至任何其他平台!

磁力计和气压计、陀螺仪、GPS等模块主要用于定位,其中磁力计主要靠测量地球的磁场来确定指向。
一般购买的 HMC5883L 三轴磁力计有两种,一种是5孔只有5V没有3.3V的,另一种是6孔有5V也有3.3V的,但是由于板上自带有稳压器,所以使用5V都没有问题。使用I2C连接,使用非常简单。

HMC5883L_Minbao.space_.jpg

 

HMC5883L_chip.jpg

I2C连接:
VIN -> 5V 或 3.3V
GND -> GND
SCL -> A5
SDA -> A4
DRDY -> 有特殊需要(每秒获取100次数据)才需要链接
(建议焊接一个排线以避免接触不良)

Library 库:
直接在I2C的库里找到HMC5883L文件夹,复制到Arduino的 Library 文件夹下,重启Arduino IDE就可以使用
(如之前没有使用过I2C,需要把I2Cdev也一并复制过去)

打开IDE,选择“文件” -> “示例” -> “HMC5883L” -> “Examples” -> “HMC5883L_raw”
或者直接拷贝下面的代码到IDE里:

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#include "Wire.h"

// I2Cdev and HMC5883L must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "HMC5883L.h"

// class default I2C address is 0x1E
// specific I2C addresses may be passed as a parameter here
// this device only supports one I2C address (0x1E)
HMC5883L mag;

int16_t mx, my, mz;

#define LED_PIN 13
bool blinkState = false;

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();

    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(38400);

    // initialize device
    Serial.println("Initializing I2C devices...");
    mag.initialize();

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(mag.testConnection() ? "HMC5883L connection successful" : "HMC5883L connection failed");
    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
}

void loop() {
    // read raw heading measurements from device
    mag.getHeading(&mx, &my, &mz);

    // display tab-separated gyro x/y/z values
    Serial.print("mag:\t");
    Serial.print(mx); Serial.print("\t");
    Serial.print(my); Serial.print("\t");
    Serial.print(mz); Serial.print("\t");
    
// To calculate heading in degrees. 0 degree indicates North
    float heading = atan2(my, mx);
    if(heading < 0)
      heading += 2 * M_PI;
    Serial.print("heading:\t");
    Serial.println(heading * 180/M_PI);

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
}

上传到Arduino Uno或其他控制板,打开“串口监视器”,选择38400波特(可以根据需要把代码修改成其他波特率),done!

爱鱼客著作权所有!未经允许不得转载:爱鱼客 » HMC5883L 三轴磁力计 电子指南针使用教程

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址