Connecting an I2C compass to Arty

In this brief post we will cover connecting an I2C compass sensor to Arty, specifically an HMC6352. The outcome is to demonstrate how to use the I2c function calls to read data from an I2C device.

See previous posts for details on the platform used, but in practice the C code can be used with any design with an IIC module, with the base address of the IP updated.

In practice this could be any I2C sensor, but the compass is nice and easy, giving feedback that is easy to interpret, as long as you know your bearings 🙂

Connect your I2C sensor to the Arty board. Use a 3v3 & GND pins for power and connect the SDA and SCL headers.

  1. Load the design onto Arty, export your design and start SDK.
  2. Next create an “Application project” in SDK. Normally this defaults to a Hello world example.
  3. Replace “hello world.c” with main.c from Github.
  4. Compile and run on device.
  5. (Windows) Open a COM port using your favorite terminal application,
    1. The baud rate is 9600.
    2. You can use “Device manager” to locate your COM port

When running you should see the heading output data will be the value in tenths of degrees from zero to 3599.

The code contains a function called LowLevelTempSensorExample that reads back this value. It is continually read and the result output on the USB UART.

while (1) {
  LowLevelTempSensorExample(IIC_BASE_ADDRESS, 0x21, sendBuffer, i2cResultBuffer);
  xil_printf("We got angle = %d\n\r", ((i2cResultBuffer[0]<<8) + i2cResultBuffer[1]));

To get this value we first need to write the “A(0x41)” command to the HMC6352. This is a single byte write. We then need to read the 2 byte response.

LowLevelTempSensorExample contains the following calls. Firstly we send the command, its pre-loaded in byte 0 of the send buffer. We pass this buffer pointer with the bytes to send to the XIic_Send function.

ByteCount = XIic_Send(IicBaseAddress, TempSensorAddress, sendBuffer, 1, XIIC_STOP;
ByteCount = XIic_Recv(IicBaseAddress, TempSensorAddress, TemperaturePtr, 2, XIIC_STOP);

Next we need to read back the two data bytes using the Xiic_Revc command. These get stored in buffer pointer to by TemperaturePtr. Note each call required the number of bytes to be written or read from or to the respective buffer. This does not include the Slave address with the R/W bit.

Finally you should be seeing terminal output similar to the following. The value should change as rotated.


One thought on “Connecting an I2C compass to Arty

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s