Notes About Working with Various Arduino & Netduino Microcontroller Boards

Wednesday, July 4, 2012

HMC6352 I2C Compass and Netduino

Note: Click here for updated version (12/03/12)

Connections:
I am using the breakout board from Spark Fun with solderless pins. Looking at the top of the breakout board with the HMC6352 label right side up, the pins from left to right are:
  • GND  --> GND on Netduino
  • VCC  --> 5v 
  • SDA  --> A4 (no pull-up resistor) 
  • SCL  --> A5 (no pull-up resistor)

Sample Code: Here is a very simple program that uses the I2C bus class to read the compass heading and print it out to the debugger's output panel in Visual Studio.

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Utilities.Helpers;

namespace Compass
{
    public class Program
    {
        public static void Main()
        {
            byte HMC6352SlaveAddr = 0x42 >> 1;
            byte HMC6352ReadCmd = 0x41; //"A"
            I2CBus bus = I2CBus.GetInstance();
            I2CDevice.Configuration config = new I2CDevice.Configuration(HMC6352SlaveAddr, 100);
            byte[] compassCmd = { HMC6352ReadCmd };
            bus.Write(config, compassCmd, 1000);
            Thread.Sleep(6);
            byte[] compassData = { 0, 0 };
            bus.Read(config, compassData, 1000);
            float headingSum = (compassData[0] << 8) + compassData[1]; 
            float heading = headingSum / 10;
            Debug.Print(heading.ToString());
        }
    }
}

No comments:

Post a Comment