/* Digital Compass by Kimio Kosaka 建築発明工作ゼミ Arduino デジタルコンパス/HMC6352 http://kousaku-kousaku.blogspot.com/2008/08/arduinohmc6352.html からHMC6352制御スケッチを模倣 */ #include //I2C通信ライブラリを取り込む #include // LCDライブラリを取り込む //LCDのピン設定 LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2); //デジタルコンパスモジュールのアドレス設定 int compassAddress = 0x42 >> 1; //=0x21 void setup() { lcd.begin(16, 2); //LCDの文字数と行数をセット lcd.clear(); //LCDをクリア Wire.begin(); //I2C通信開始 Wire.beginTransmission(compassAddress); //Continuous Modeに設定する Wire.send('G'); //RAM書き込み用コマンド Wire.send(0x74); //書き込み先指定 Wire.send(0x72); //モード設定 Wire.endTransmission(); //通信終了 delayMicroseconds(70); //処理時間 } void loop() { float degree; lcd.setCursor(0,0); lcd.print("Magnetic Heading"); lcd.setCursor(0,1); degree = get_heading(); if(degree < 10.0) lcd.print(" "); if(degree < 100.0) lcd.print(" "); lcd.print(degree); //次の処理のために少し待つ(20Hz) delay(50); } // Heading方位を得る関数 float get_heading() { int reading = 0; //読み込み値(角度)の変数を用意 Wire.requestFrom(compassAddress, 2); //デバイスに2バイト分のデータを要求する while(Wire.available()<2); //要求したデータが2バイト来るまで待つ reading = Wire.receive(); //1バイト分のデータの読み込み reading = reading << 8; //読み込んだデータを8ビット左シフトしておく reading += Wire.receive();//次の1バイト分のデータを読み込み,一つ目のデータと合成 return (float) reading / 10; //2バイト分のデータを10で割って関数の値とする }