I2C driver for HMC5583L digital compass sensor
hmc5583l.cpp@1:097089f0feb1, 2015-12-19 (annotated)
- Committer:
- sillevl
- Date:
- Sat Dec 19 10:40:55 2015 +0000
- Revision:
- 1:097089f0feb1
- Parent:
- 0:91f08ac76444
add constructor that accepts I2C object
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
sillevl | 0:91f08ac76444 | 1 | #include "hmc5583l.h" |
sillevl | 0:91f08ac76444 | 2 | #include "stdint.h" |
sillevl | 0:91f08ac76444 | 3 | |
sillevl | 1:097089f0feb1 | 4 | HMC5583L::HMC5583L(I2C &_i2c, int _address): i2c(_i2c), address(_address) |
sillevl | 1:097089f0feb1 | 5 | { |
sillevl | 1:097089f0feb1 | 6 | initialize(); |
sillevl | 1:097089f0feb1 | 7 | } |
sillevl | 1:097089f0feb1 | 8 | |
sillevl | 0:91f08ac76444 | 9 | HMC5583L::HMC5583L(PinName sda, PinName scl, int _address): i2c(sda, scl), address(_address) |
sillevl | 0:91f08ac76444 | 10 | { |
sillevl | 1:097089f0feb1 | 11 | initialize(); |
sillevl | 1:097089f0feb1 | 12 | } |
sillevl | 1:097089f0feb1 | 13 | |
sillevl | 1:097089f0feb1 | 14 | void HMC5583L::initialize() |
sillevl | 1:097089f0feb1 | 15 | { |
sillevl | 0:91f08ac76444 | 16 | char data[2]; |
sillevl | 0:91f08ac76444 | 17 | data[0] = 0x02; // select mode register |
sillevl | 0:91f08ac76444 | 18 | data[1] = 0x00; // continous measurement mode |
sillevl | 0:91f08ac76444 | 19 | |
sillevl | 1:097089f0feb1 | 20 | i2c.write(address, data, 2); |
sillevl | 0:91f08ac76444 | 21 | } |
sillevl | 0:91f08ac76444 | 22 | |
sillevl | 0:91f08ac76444 | 23 | coord HMC5583L::getCompass() |
sillevl | 0:91f08ac76444 | 24 | { |
sillevl | 0:91f08ac76444 | 25 | coord c; |
sillevl | 0:91f08ac76444 | 26 | // tell where to begin reading data |
sillevl | 0:91f08ac76444 | 27 | char data[] = {0x03}; // select register 3, MSB register |
sillevl | 0:91f08ac76444 | 28 | i2c.write(address, data, 1); |
sillevl | 0:91f08ac76444 | 29 | |
sillevl | 0:91f08ac76444 | 30 | char values[6]; |
sillevl | 0:91f08ac76444 | 31 | i2c.read(address, values, 6); |
sillevl | 0:91f08ac76444 | 32 | |
sillevl | 0:91f08ac76444 | 33 | // x = (x >> 11) == 0 ? x : -1 ^ 0xFFF | x; |
sillevl | 0:91f08ac76444 | 34 | c.x = regToInt(values[0], values[1]); |
sillevl | 0:91f08ac76444 | 35 | c.y = regToInt(values[2], values[3]); |
sillevl | 0:91f08ac76444 | 36 | c.z = regToInt(values[4], values[5]); |
sillevl | 0:91f08ac76444 | 37 | |
sillevl | 0:91f08ac76444 | 38 | return c; |
sillevl | 0:91f08ac76444 | 39 | } |
sillevl | 0:91f08ac76444 | 40 | |
sillevl | 0:91f08ac76444 | 41 | int HMC5583L::regToInt(char msb, char lsb){ |
sillevl | 0:91f08ac76444 | 42 | int16_t value = msb << 8 | lsb; |
sillevl | 0:91f08ac76444 | 43 | return (int) value; |
sillevl | 0:91f08ac76444 | 44 | } |