#include <Wire.h>

#define BAUD_RATE    9600
#define HALF_SECOND  500
#define LED          13
#define MSB          0
#define LSB          1
#define OFF          0x00
#define ON           0x01

/*
   Modified by Roy Vanegas (13 February 2010):
   
      http://roy.vanegas.org/itp/thesis/

   Modified by Vaibhav Bhawsar:

      http://recombine.net/blog/article/49/hmc6352-sparkfun-compass-and-arduino

   Original Code posted on Sparkfun's Web site:

      http://forum.sparkfun.com/viewtopic.php?t=6236
*/

/* -------------------------------------------------------------------
   SETUP
   ---------------------------------------------------------------- */
void setup( void )
{
   Serial.begin( BAUD_RATE );

   pinMode( LED, OUTPUT );

   Wire.begin();
}

/* -------------------------------------------------------------------
   LOOP
   ---------------------------------------------------------------- */
void loop( void )
{
   static short i;
   static int direction;
   static byte direction_data[ 2 ];
   static boolean led_state = false;

   if( (led_state = !led_state) )
      digitalWrite( LED, ON );
   else
      digitalWrite( LED, OFF );

   Wire.beginTransmission( 0x21 );
   Wire.send( "A" );
   Wire.endTransmission();

   delay( 6 );

   Wire.requestFrom( 0x21, 2 );

   i = 0;

   while( ( Wire.available() ) && ( i < 2 ) )
      direction_data[ i++ ] = Wire.receive();

   direction = ( direction_data[ MSB ] * 256 ) + direction_data[ LSB ];

   Serial.print( "Current heading: " );
   Serial.print( int ( direction / 10 ) );
   Serial.print( "." );
   Serial.print( int ( direction % 10 ) );
   Serial.print( " degrees\r\n" );

   delay( HALF_SECOND );
}