磁力計

参考:

 
使用している磁気センサーは MAG3110
 
プログラムをアップロードすると micro:bit に "DRAW A CIRCLE" と表示されてキャリブレーション (micro:bit をぐるっと全方向に傾ける操作) が要求される。それ以外の場合でも compass.calibrate() を呼べば micro:bit 側からキャリブレーションが要求される。
 

  • compass.heading()
    方位を 0 ~ 359 の整数で返す。北が 0、東が 90、南が 180、西が 270。
from microbit import *

while True:
    if button_a.is_pressed():
        compass.calibrate()
        
    heading = compass.heading()
    
    if 45 < heading and heading <= 135:
        display.show("E")
    elif 135 < heading and heading <= 225:
        display.show("S")
    elif 225 < heading and heading <= 315:
        display.show("W")
    else:
        display.show("N")
    
    sleep(10)


 
――――――――――――――――――――――――――――

  • compass.get_*()
    磁力は軸ごとに取得することもできる。
  • compass.get_field_strength()
    磁界強度も取得できる。
from microbit import *

while True:
    x,y,z    = compass.get_x(), compass.get_y(), compass.get_z()
    heading  = compass.heading()
    strength = compass.get_field_strength()
    
    print("{} {} {}".format(x, y, z))
    print("heading " + str(heading))
    print("strength " + str(strength))    
    
    sleep(1000)

 
Lua は聯結演算子を使って数値と文字列とが直接聯結できるが、Python はそうはゆかず str() で型キャストしなければならない。
f:id:ti-nspire:20171226120516p:plain:w300