首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

HMC5883L 電子羅盤校準指南:樹莓派實作磁場干擾過濾與硬鐵/軟鐵校正

     編輯:關於C++

HMC5883L 電子羅盤完整校準指南

本文適用所有電子羅盤校準,不限 HMC5883L。針對固定強度與方向的磁場干擾(如機器人自身馬達、電路板產生的硬鐵干擾),透過校準消除偏移量。環境變動干擾(如喇叭磁鐵)無法靜態校準消除。

校準原理:硬鐵干擾補償

將感測器平放於水平面,繞 Z 軸緩慢旋轉 360°。地磁場在 XY 平面分量描繪標準圓,硬鐵干擾導致圓心偏移。所有測量值的平均值即為硬鐵偏移量。

樹莓派 Python 讀取原始資料

#!/usr/bin/python
import smbus, time, math

bus = smbus.SMBus(0)  # Rev 1 Pi 用 0,Rev 2+ 用 1
addr = 0x1e

def read_word_2c(reg):
    high = bus.read_byte_data(addr, reg)
    low = bus.read_byte_data(addr, reg + 1)
    val = (high << 8) + low
    return -((65535 - val) + 1) if val >= 0x8000 else val

def write_byte(reg, val):
    bus.write_byte_data(addr, reg, val)

# 初始化 HMC5883L
write_byte(0, 0b01110000)  # 8 samples @ 15Hz
write_byte(1, 0b00100000)  # 1.3 gain, 1090 LSB/Gauss
write_byte(2, 0b00000000)  # 連續量測模式

scale = 0.92  # mG/LSB 對應 1.3 gain

# 采集 500 筆資料(約 50 秒)
for i in range(500):
    x = read_word_2c(3)
    y = read_word_2c(7)
    z = read_word_2c(5)
    bearing = math.atan2(y, x)
    if bearing < 0: bearing += 2 * math.pi
    print(x, y, x * scale, y * scale)
    time.sleep(0.1)

資料視覺化:Gnuplot 繪製 XY 散佈圖

# 執行采集並存檔
sudo ./compass.py > compass-plot.dat

# Gnuplot 腳本
set terminal wxt persist size 800,800 background '#000000'
set style line 99 linecolor rgb "#ffffff" linetype 0 linewidth 2
set key topright textcolor linestyle 99
set grid linestyle 99
set border linestyle 99
plot 'compass-plot.dat' using 1:2 title "Raw compass values" linecolor rgb "green"
gnuplot -e "filename='compass-plot.dat'" gnuplot-compass.plg

未校準 XY 散佈圖:圓心偏離原點

計算偏移量並套用校準

minx = maxx = miny = maxy = 0
for i in range(500):
    x = read_word_2c(3)
    y = read_word_2c(7)
    if x < minx: minx = x
    if x > maxx: maxx = x
    if y < miny: miny = y
    if y > maxy: maxy = y
    time.sleep(0.1)

offset_x = (maxx + minx) / 2
offset_y = (maxy + miny) / 2
print(f"X offset: {offset_x}, Y offset: {offset_y}")
# 輸出範例:X offset: -10, Y offset: 10

套用偏移修正後的讀取程式碼

x_offset = -10
y_offset = 10

x = (read_word_2c(3) - x_offset) * scale
y = (read_word_2c(7) - y_offset) * scale
z = read_word_2c(5) * scale

bearing = math.atan2(y, x)
if bearing < 0: bearing += 2 * math.pi
print(f"Heading: {math.degrees(bearing):.1f}°")

Z 軸校準

同理,將感測器固定使 XZ 平面水平,繞 Y 軸旋轉 360°,計算 Z 軸偏移並套用。

進階:軟鐵干擾校正(橢圓擬合)

若散佈圖呈橢圓而非圓,存在軟鐵干擾(鐵磁材料扭曲磁場)。需用橢圓擬合演算法計算變換矩陣,將橢圓映射回標準圓。此為進階主題,超出本文範圍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved