Uncategorized

HMC5883L heading – Raspberry Pi Forums


Hello, I would like to get a heading value from HMC5883L. The values I am getting are strange and unexpected. I am using the correct declination angle and there are no magnetic elements around the sensor (see photo). I have used this sensor in an arduino quadcopter with my flight controller and it worked fine without the need for any offsets. Any ideas? (It looks like a magnetometer sensitivity problem and heading scale at all) Image on google drive: https://drive.google.com/file/d/1eI0mKh … sp=sharing

Sample code:

Code: Select all

import smbus
import math
import time

HMC5883L_ADDRESS = 0x1E
CONFIG_REGISTER_A = 0x00
CONFIG_REGISTER_B = 0x01
MODE_REGISTER = 0x02
DATA_X_MSB = 0x03
DATA_X_LSB = 0x04
DATA_Z_MSB = 0x05
DATA_Z_LSB = 0x06
DATA_Y_MSB = 0x07
DATA_Y_LSB = 0x08

declination = 5.75

bus = smbus.SMBus(1)

def setup_hmc5883l():
    bus.write_byte_data(HMC5883L_ADDRESS, MODE_REGISTER, 0x00)

def read_raw_data(register):
    high = bus.read_byte_data(HMC5883L_ADDRESS, register)
    low = bus.read_byte_data(HMC5883L_ADDRESS, register + 1)
    value = (high << 8) + low
    if value > 32767:
        value -= 65536
    return value

def read_hmc5883l():
    x = read_raw_data(DATA_X_MSB)
    z = read_raw_data(DATA_Z_MSB)
    y = read_raw_data(DATA_Y_MSB)
    heading_rad = math.atan2(y, x)
    heading_rad += math.radians(declination)
    if heading_rad < 0:
        heading_rad += 2 * math.pi
    heading_deg = math.degrees(heading_rad)
    return heading_deg

if __name__ == "__main__":
    try:
        setup_hmc5883l()
        while True:
            heading = read_hmc5883l()
            print(f"Heading: {heading:.2f} degrees")
            time.sleep(1)

    except KeyboardInterrupt:
        print("konec")



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *