Wite.begin関数
Arduino⇔I2Cに対応したセンサーモジュール等で通信を開始する前に使用します。
使用例
#include <Wire.h> //I2C Arduino Library #define address 0x1E //0011110b, I2C 7bit address of HMC5883 void setup() { //GY-273 Serial.begin(9600); Wire.begin(); Wire.beginTransmission(address); //open communication with HMC5883 Wire.write(0x02); //select mode register Wire.write(0x00); //continuous measurement mode Wire.endTransmission(); } void loop() { Serial.println(Angleread()) ; // 方位角を返す delay(500) ; // 500ms後に繰り返す } int Angleread() { int x, y, z; //triple axis data Wire.beginTransmission(address); Wire.write(0x03); //select register 3, X MSB register Wire.endTransmission(); Wire.requestFrom(address, 6); if (6 <= Wire.available()) { x = Wire.read() << 8; //X msb x |= Wire.read(); //X lsb z = Wire.read() << 8; //Z msb z |= Wire.read(); //Z lsb y = Wire.read() << 8; //Y msb y |= Wire.read(); //Y lsb } return atan2((x + 20) , (y + 20) * (-1)) * RAD_TO_DEG + 180; //40と20は補正値 }
図1:プログラム例
以下補足です
※1:Wireライブラリ
※2:I2C
I2C(Inter-Integrated Circuit、アイ・スクエアド・シー)はフィリップス社で開発されたシリアルバスです。
※3:バス
バス(bus)とは、コンピュータの内外、各回路がデータを交換するための共通の経路の事です。
※4,5:マスタ,スレーブ
I2Cインターフェースは1対n(1以上)の同期式シリアル通信で、1がマスターでnがスレーブとなっています。※伝送距離は装置内程度と非常に短い。
I2Cは通信する相手のアドレスをデータとして送りスレーブとの通信(送受信)を確立します、つまりI2Cはマスターからアクションを起こさないとスレーブとは送受信が出来ません。
送受信に使う配線が1本(SDA)、マスターと同期を取る為に送信するクロック信号が1本の計2本と、配線が少なくて済むのがI2C通信による最大のメリットです。