Honeywell HMC6352 digital compass library.

Dependents:   CanSat-C_test test AvoidTest Run-Avoid

HMC6352.cpp

Committer:
miyajitakenari
Date:
2021-11-06
Revision:
2:0a44cb78fd9a
Parent:
0:83c0cb554099

File content as of revision 2:0a44cb78fd9a:

#include "HMC6352.h"

HMC6352::HMC6352(PinName sda, PinName scl) {

    i2c_ = new I2C(sda, scl);
    //100KHz, as specified by the datasheet.
    i2c_->frequency(100000);

    operationMode_ = getOpMode();

}

int HMC6352::sample(void) {

    char tx[1];
    char rx[2];

    if (operationMode_ == HMC6352_STANDBY || operationMode_ == HMC6352_QUERY) {
        tx[0] = HMC6352_GET_DATA;

        i2c_->write((HMC6352_I2C_ADDRESS << 1) & 0xFE, tx, 1);
        wait_ms(1);
    }

    i2c_->read((HMC6352_I2C_ADDRESS << 1) | 0x01, rx, 2);
    wait_ms(1);

    return (((int)rx[0] << 8) | (int)rx[1]);

}

void HMC6352::setCalibrationMode(int exitOrEnter) {

    char tx[1];
    int delay = 0;

    tx[0] = exitOrEnter;

    if (exitOrEnter == HMC6352_EXIT_CALIB) {
        delay = 15;
    } else if (exitOrEnter == HMC6352_ENTER_CALIB) {
        delay = 1;
    }

    i2c_->write((HMC6352_I2C_ADDRESS << 1) & 0xFE, tx, 1);
    wait_ms(delay);

}

int HMC6352::getOpMode(void) {

    int response = 0;

    response = read(HMC6352_RAM_READ, HMC6352_RAM_OPMODE);

    return (response & 0x00000003);

}

void HMC6352::setOpMode(int mode, int periodicSetReset, int measurementRate) {

    char opModeByte = mode;

    if (periodicSetReset == 1) {
        opModeByte |= HMC6352_PERIODIC_SR;
    }

    if (measurementRate == 5) {
        opModeByte |= HMC6352_CM_MR_5HZ;
    } else if (measurementRate == 10) {
        opModeByte |= HMC6352_CM_MR_10HZ;
    } else if (measurementRate == 20) {
        opModeByte |= HMC6352_CM_MR_20HZ;
    }

    write(HMC6352_RAM_WRITE, HMC6352_RAM_OPMODE, opModeByte);
    write(HMC6352_EEPROM_WRITE, HMC6352_OPMODE, opModeByte);

    operationMode_ = mode;

}

void HMC6352::write(int EepromOrRam, int address, int data) {

    char tx[3];

    tx[0] = EepromOrRam;
    tx[1] = address;
    tx[2] = data;

    i2c_->write((HMC6352_I2C_ADDRESS << 1) & 0xFE, tx, 3);
    wait_ms(1);

}

int HMC6352::read(int EepromOrRam, int address) {

    char tx[2];
    char rx[1];

    tx[0] = EepromOrRam;
    tx[1] = address;

    i2c_->write((HMC6352_I2C_ADDRESS << 1) & 0xFE, tx, 2);
    wait_ms(1);
    i2c_->read((HMC6352_I2C_ADDRESS << 1) | 0x01, rx, 1);
    wait_ms(1);

    return (rx[0]);

}