参考:
- Programming the BBC micro:bit: Getting Started with MicroPython (English Edition), pp.99-102
- micro:bitではじめるプログラミング ―親子で学べるプログラミングとエレクトロニクス (Make:PROJECTS), pp.54-59
使用している磁気センサーは 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)
――――――――――――――――――――――――――――
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() で型キャストしなければならない。