本文適用所有電子羅盤校準,不限 HMC5883L。針對固定強度與方向的磁場干擾(如機器人自身馬達、電路板產生的硬鐵干擾),透過校準消除偏移量。環境變動干擾(如喇叭磁鐵)無法靜態校準消除。
將感測器平放於水平面,繞 Z 軸緩慢旋轉 360°。地磁場在 XY 平面分量描繪標準圓,硬鐵干擾導致圓心偏移。所有測量值的平均值即為硬鐵偏移量。
#!/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)
# 執行采集並存檔 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

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}°")
同理,將感測器固定使 XZ 平面水平,繞 Y 軸旋轉 360°,計算 Z 軸偏移並套用。
若散佈圖呈橢圓而非圓,存在軟鐵干擾(鐵磁材料扭曲磁場)。需用橢圓擬合演算法計算變換矩陣,將橢圓映射回標準圓。此為進階主題,超出本文範圍。