Skip to main content

GR-COTTON Special Project: Digital Compass (HMC5883L)

Overview

This program introduces attaching a digital compass (HMC5883L) to the GR-COTTON board in order to determine orientation.

This project and description are still under development! The sample program can read the sensor’s values, but cannot yet calculate orientation.

cotton-sp-hmc5883l-serial

Preparation

You will need a GR-COTTON board, a USB cable (Micro B type), and an HMC5883L module.

You will need to install a pin socket on GR-COTTON and a pin header on the HMC5883L module.

The pin socket can be purchased from the Akizuki Denshi website.

cotton-sp-prepare-hmc5883l

Connect the HMC5883L module to GR-COTTON as shown in the photo to the right.

Make sure the white jumper on the reverse side of GR-COTTON is moved to the “3V3 USB” side. If it is set to the BATT side, remove and reinsert it into the USB side.

cotton-sp-prepare-hmc5883l-con
cotton-sp-prepare2

Displaying Digital Compass Reading on Serial Monitor

This sample programs the serial monitor to display readings taken every half-second by the digital compass.


#include <arduino.h>
#include <Wire.h>
 
#define HMC5883L_ADDRESS 0x1E //7bit ADDRESS
 
//*********************************************************
void setup() 
{
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();
   
  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(HMC5883L_ADDRESS);
  Wire.write(0x02); //select mode register
  Wire.write(0x00); //continuous measurement mode
  Wire.endTransmission();
 
}
//------------------------------------------------------
void loop() 
{
  int x,y,z; //triple axis data
   
  //set address where to begin reading data
  Wire.beginTransmission(HMC5883L_ADDRESS);
  Wire.write(0x03); //select register 3, X MSB register
  Wire.endTransmission();
  
 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(HMC5883L_ADDRESS, 6);
  if(6  < = Wire.available()){
    x = Wire.read() << 8;  x |= Wire.read();
    z = Wire.read() << 8;  z |= Wire.read();
    y = Wire.read() << 8;  y |= Wire.read();
  }
   
  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);  
    
  delay(500);
 
}