#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
|