Monday, 3 February 2014

HELP GY273 compass on I2C bus

GY273 compass on I2C bus

Here’s an example using the GY273 compass and the Wire.h library. The GY273 detects three axes for magnetic field. It uses the Honeywell HMC5883L chip.

Screen Shot 2014 02 03 at 13 10 09

Top view of chip, arrow shows +ve output for the axis direction. The module has an I2C address of 0x1E.

Screen Shot 2014 02 03 at 13 10 35


// compass module GY273 I2C
/* connections
GY273    Arduino
VCC       3.3V
GND       GND
SCL       A5
SDA       A4
DRDY      not used
*/

#include "Wire.h"

// module I2C address
#define GY273ADDR 0x1E

// register addresses for Axes X, Y and Z data, see table above
#define X 0x03
#define Z 0x05
#define Y 0x07


void setup() 
{
  Serial.begin(9600);
  
  Wire.begin(); // create wire object
 
  initGY273(); // initialise module
}

void loop() 
{
  /* Read each sensor axis data and output to the serial port */
  Serial.print(GY273read(X));
  Serial.print(" ");
  Serial.print(GY273read(Y));
  Serial.print(" ");
  Serial.println(GY273read(Z));
  
  // Wait a little before reading again
  delay(500);
}


// initialise module
void initGY273(void)
{
  // Set the module to 8x averaging, 15Hx rate
  Wire.beginTransmission(GY273ADDR);
  Wire.write(0x00); // config reg A
  Wire.write(0x70); // 0 11 100 00
          
  // Set a gain of 1090 (default), range +/-1.3Ga, gain 1090
  Wire.write(0x01); // config reg B
  Wire.write(0x20); // 001 00000
  Wire.endTransmission();
}


// read from X, Y or Z data registers 
// return 16 bit signed int
int GY273read(byte Axis)
{
  int r;
  
  // single measurement mode
  Wire.beginTransmission(GY273ADDR);
  Wire.write(0x02); // mode register
  Wire.write(0x01); // 000000 01
  Wire.endTransmission();
  delay(50); // was 6
  
  // move register pointer 
  Wire.beginTransmission(GY273ADDR);
  Wire.write(Axis); // to one of the axis data registers 0x03, 0x05 or 0x07
  Wire.endTransmission();
   
  // Read the 2 bytes of data, concatenate and return 
  Wire.requestFrom(GY273ADDR, 2);  
  r = Wire.read() << 8; // shift L for 8 MSB, reads register 0x03...
  r |= Wire.read(); // add LSB to make int, reads register 0x04...
  return r;
}

No comments: