micro:bit / I2C バス / オンボード加速度計 / I2C バスから 3 軸の 10 ビットデータを読み取る / MicroPython

from microbit import *
#i2c.write(0x1d, bytes([0x2a, 1<<1]))

def raw2g(raw):
    if 0b1000000000 == (0b1000000000 & raw):
        raw -= 2**10
    
    return 4/(2**10) * raw
    
while True:
    raw = i2c.read(0x1d, 7)
    
    raw_x =  (raw[1]<<2)|(raw[2]>>6)
    raw_y =  (raw[3]<<2)|(raw[4]>>6)
    raw_z =  (raw[5]<<2)|(raw[6]>>6)
    
    g_x = raw2g(raw_x)
    g_y = raw2g(raw_y)
    g_z = raw2g(raw_z)
    
    print("x: %.7f, y: %.7f, z: %.7f" % (g_x, g_y, g_z))
    sleep(500)

実行結果:
f:id:ti-nspire:20180530140239p:plain