i2c 2

Dependencies:   mbed

Revision:
0:bf86efb237ca
Child:
1:b38a436a0059
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Apr 22 17:24:36 2022 +0000
@@ -0,0 +1,117 @@
+/*
+MPU9250をi2c通信してみた。
+
+1バイトずつ送受信する場合は、スタートコンディション・ストップコンディションなどのアドレス送信などの制御が必要です。
+連続だったら、いいらしい。(参照 https://os.mbed.com/users/okini3939/notebook/I2C_jp/ )
+
+「マスターが受信する」によって、取得するため
+
+1.slave address(スレーブアドレス→内部レジスタ)
+
+2.ack(受信)
+3.data1(8bits)
+4.ack=1(送信)
+5.data2(8bits)
+6.ack=1(送信)
+
+(参照 http://www.picfun.com/c15.html )
+*/
+
+#include "mbed.h"
+
+Serial pc(USBTX,USBRX);
+I2C i2c(p9, p10);
+
+const int addr = 0xD0;   //加速度とジャイロのスレーブアドレス
+
+short int xl,xh; //x軸の加速度
+short int yl,yh; //y軸の加速度
+short int zl,zh;
+
+int main()
+{
+    i2c.frequency(100000);
+    pc.printf("Start!!\r\n");
+    
+    while(1) {
+        //x軸加速度取得
+        
+        //1.slave address(スレーブアドレス→内部レジスタ)
+        i2c.start();
+        i2c.write(addr);// slaveアドレス
+        i2c.write(0x3b);// 内部レジスタ(59)
+        i2c.stop();
+        
+        //2.ack=0(受信)
+        i2c.start();
+        i2c.read(false); //ack(受信)
+        //3.data1(8bits)
+        i2c.write(0x3c);//data1(60)1
+        i2c.stop();
+        
+        //4.ack=0(送信)
+        i2c.start();
+        i2c.write(addr|0x01); //ack=1(送信)
+        xh = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        i2c.start();
+        //5.data2(8bits)
+        i2c.write(0x3d);//data2(61)2
+        //6.ack=1(送信)
+        i2c.write(addr|0x01); //ack=1(受信)
+        xl = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        //以下2~6を繰り返す。
+        
+        
+        //y軸加速度取得
+        i2c.start();
+        i2c.read(false); //ack(受信)
+        i2c.write(0x3e); //data(62)3
+        i2c.stop();
+        
+        i2c.start();
+        i2c.write(addr|0x01); //ack=1(送信)
+        yh = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        i2c.start();
+        i2c.write(0x3f); //data(63)4
+        i2c.write(addr|0x01); //ack=1(送信)
+        yl = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        //z軸加速度取得
+        i2c.start();
+        i2c.read(false); //ack(受信)
+        i2c.write(0x40); //data(64)5
+        i2c.stop();
+        
+        i2c.start();
+        i2c.write(addr|0x01); //ack=1(送信)
+        zh = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        i2c.start();
+        i2c.write(0x41); //data(65)6
+        i2c.write(addr|0x01); //ack=1(送信)
+        zl = i2c.read(0);//data取り出す
+        i2c.stop();
+        
+        
+        
+        
+        double  acc_ax = short((xh<<8) | (xl));
+        double  acc_ay = short((yh<<8) | (yl));
+        double  acc_az = short((zh<<8) | (zl));
+        
+        double AX = (acc_ax)*2/32768*9.81;
+        double AY = (acc_ay)*2/32768*9.81;
+        double AZ = (acc_az)*2/32768*9.81;
+        
+        pc.printf("%f %f %f\r\n",AX,AY,AZ);
+        wait(0.01);
+    }
+}
\ No newline at end of file