micro:bit / I2C バス / オンボード加速度計 / I2C バスから 3 軸の 10 ビットデータを読み取る / mbed
#include "MicroBit.h" MicroBit uBit; float raw2g(int raw){ if(0x200 == (0x200 & raw)){ // 0x200 = 0b 10 0000 0000 raw -= 1024; // 1024 = 2^10 } return 0.00390625 * (float)raw; // 0.00390625 = 4/(2^10) } int main(void){ uBit.init(); char buf[] = {0x01}; char buf2[6]; while(1){ uBit.i2c.write(0x1d<<1, buf, 1, true); uBit.i2c.read(0x1d<<1, buf2, 6); int raw_x = (buf2[0]<<2) | (buf2[1]>>6); int raw_y = (buf2[2]<<2) | (buf2[3]>>6); int raw_z = (buf2[4]<<2) | (buf2[5]>>6); float x = raw2g(raw_x); float y = raw2g(raw_y); float z = raw2g(raw_z); printf("x: %.8f , y: %.8f , z: %.8f\n", x, y, z); wait_ms(1000); } release_fiber(); return 0; }
実行結果: