方位を調べてみよう

方位センサー

ここでは、parallaxで販売しているHMC5883Lという方位センサーを使ってみます。このデバイスはI2Cプロトコルのデバイスですので簡単なEEPROMのコントロールなどを先に理解してください。


ヘッダーファイル

HMC5883L.h
#ifndef HMC5883L_H
#define HMC5883L_H

#include <mbed.h>
#include <I2C.h>

class HMC5883L : public I2C
{
  public:
    unsigned char address;
    HMC5883L();
    void write(unsigned char control, unsigned char  dt);
    void readData(short*);
    int readData();
  protected:
  private:
    void init();
};

#endif // HMC5883L_H
 1 
 2 
 3 
 4 
 5 
 6 
 7 I2Cクラスから継承される
 8 
 9 
10 デバイスのアドレス
11 コンストラクタ
12 値の設定用メソッド
13 生データを読むメソッド
14 測定し方位を得るメソッド
15 
16 
17 初期化メソッド
18 
19 
20 


クラスファイル



HMC5883L.cpp
#include "HMC5883L.h"

HMC5883L::HMC5883L():I2C(p28,p27) // sda, scl
{
  init();
}

void HMC5883L::init()
{
  address = 0x3C;
  write(0,0x70);  // 8-average,15Hz default, normal measurement mode
  write(1,0xa0);  // Gain=5
}

void HMC5883L::write(unsigned char control, unsigned char  dt)
{
  start();
  ((I2C*)this)->write(address);
  ((I2C*)this)->write(control);
  ((I2C*)this)->write(dt);
  stop();
}

void HMC5883L::readData(short* data)
{
  write(2,1);
  wait_ms(6);
  start();
  ((I2C*)this)->write(address|1);
  unsigned char high, low;
  for(int i=0; i<3; i++) {
    high = ((I2C*)this)->read(1);
    low  = ((I2C*)this)->read((i==2)?0:1);
    data[i] = (short)(((high) << 8) | low);
  }
  stop();
}

/*
北を0度として反時計回りに角度を求める
*/
int HMC5883L::readData()
{
  short raw[3];
  readData(raw);
  int x = raw[2];
  int y = raw[0];
  double dir = atan(x>y ? (double)y/x: (double)x/y);
  double degree=dir*180/M_PI;
  if(x>=0)
  {
    if(y>=0){
      if(x>y) dir = degree;
      else    dir = 90-degree;
    }
    else      dir = 360+degree;
  }
  else
  {
    if(y<0)
    {
      if(x>y) dir = 180+degree;
      else    dir = 270-degree;
    }
    else      dir = 90-degree;
  }
  return (int)dir;
}
 1 
 2 
 3 コンストラクタ
 4 
 5 
 6 
 7 
 8 初期化メソッド
 9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 0~359度に変換する
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 


メインプログラム


ここでは、I2CのLCDに表示するようにしています。
main.cpp
#include "HMC5883L.h"
#include "I2CLCD.h"

int main()
{
  I2CLCD lcd(p9,p10);
  HMC5883L compass;
  while(true)
  {
    int degree = compass.readData();
    lcd.write(degree,5,0);
    lcd.home();
  }
}
 1 
 2 
 3 
 4 
 5 
 6 I2CのLCDオブジェクト
 7 方位センサーのオブジェクト
 8 
 9 
10 方位を測定する
11 表示
12 
13 
14 


方位とモーションを両方同時に調べてみよう