Rev Author Line No. Line
2985 kaklik 1 // i2c slave addresses
2 #define HMC5883L_WRT_ADDR 0x3C
3 #define HMC5883L_READ_ADDR 0x3D
2926 jacho 4  
2985 kaklik 5 // Register addresses
6 #define HMC5883L_CFG_A_REG 0x00
7 #define HMC5883L_CFG_B_REG 0x01
8 #define HMC5883L_MODE_REG 0x02
9 #define HMC5883L_X_MSB_REG 0x03
2926 jacho 10  
2985 kaklik 11 //------------------------------
12 // Low level routines
13 //------------------------------
14 void hmc5883l_write_reg(int8 reg, int8 data)
15 {
16 i2c_start();
17 i2c_write(HMC5883L_WRT_ADDR);
18 i2c_write(reg);
19 i2c_write(data);
20 i2c_stop();
2926 jacho 21 }
22  
2985 kaklik 23 //------------------------------
24 int8 hmc5883l_read_reg(int8 reg)
2926 jacho 25 {
2985 kaklik 26 int8 retval;
2926 jacho 27  
2985 kaklik 28 i2c_start();
29 i2c_write(HMC5883L_WRT_ADDR);
30 i2c_write(reg);
31 i2c_start();
32 i2c_write(HMC5883L_READ_ADDR);
33 retval = i2c_read(0);
34 i2c_stop();
2926 jacho 35  
2985 kaklik 36 return(retval);
2926 jacho 37 }
38  
2985 kaklik 39 //------------------------------
40 typedef struct
2926 jacho 41 {
2985 kaklik 42 signed int16 x;
43 signed int16 y;
44 signed int16 z;
45 }hmc5883l_result;
2926 jacho 46  
2985 kaklik 47 // This global structure holds the values read
48 // from the HMC5883L x,y,z registers.
49 hmc5883l_result compass = {0,0,0};
2926 jacho 50  
2985 kaklik 51 //------------------------------
52 void hmc5883l_read_data(void)
2926 jacho 53 {
2985 kaklik 54 unsigned int8 x_lsb;
55 unsigned int8 x_msb;
2926 jacho 56  
2985 kaklik 57 unsigned int8 y_lsb;
58 unsigned int8 y_msb;
2926 jacho 59  
2985 kaklik 60 unsigned int8 z_lsb;
61 unsigned int8 z_msb;
2926 jacho 62  
2985 kaklik 63 i2c_start();
64 i2c_write(HMC5883L_WRT_ADDR);
65 i2c_write(HMC5883L_X_MSB_REG); // Point to X-msb register
66 i2c_start();
67 i2c_write(HMC5883L_READ_ADDR);
2926 jacho 68  
2985 kaklik 69 x_msb = i2c_read();
70 x_lsb = i2c_read();
2926 jacho 71  
2985 kaklik 72 z_msb = i2c_read();
73 z_lsb = i2c_read();
2926 jacho 74  
2985 kaklik 75 y_msb = i2c_read();
76 y_lsb = i2c_read(0); // do a NACK on last read
77  
78 i2c_stop();
79  
80 // Combine high and low bytes into 16-bit values.
81 compass.x = make16(x_msb, x_lsb);
82 compass.y = make16(y_msb, y_lsb);
83 compass.z = make16(z_msb, z_lsb);
2926 jacho 84 }
85