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