Loginskip to content

HiTechnic Digital Compass driver for RobotC

news/
NXT Repository/Programming/

I’ve written a simple device driver for the HiTechnic digital compass sensor. The driver hides all hardware details (i.e. I2C communication) from the user, allowing easy integration of the new sensor into existing programs. It polls the sensor reading every 5ms into the standard sensor variables SensorRaw and SensorValue.

The following sample program demonstrates the use the driver:

// Add the driver code
#include “HTCompass.c”
//Assign port
const tSensors myCompass = S4;
task main()
{
// Define sensor type and subtype as HiTechnic Digital Compass sensor
SensorType[myCompass] = HTCompassSensor;
SensorSubType[myCompass] = HTCompassSubType;

// Start compass driver.
StartTask(HTCmpsDriver);

// Calculate relative heading from 23 degrees
nHTCmpsRelativeHeading[myCompass] = 23;

while(1)
{
//Display heading
nxtDisplayTextLine(5,” Heading: %d”, SensorRaw[myCompass]);
nxtDisplayTextLine(6,” Deviation: %d”, SensorValue[myCompass]);

// wait a little
wait1Msec(1);
}
StopAllTasks();
}

The above code demonstrates how to read both “raw” heading (exact heading 0..359) and the deviation from a predefined value. The value in nHTCmpsRelativeHeading can be set at any time, setting a new “relative” heading direction.

To use the driver one need the HTCompass.c file available here. Also, one must use the latest RobotC version, as older versions did not allow writing into SensorRaw. The current RobotC version (v. 1.0.21A) still defines SensorRaw as “const”, but in firmware this variable is read/write, and future versions of RobotC will correct this. In the mean time, one should manually change the line

intrinsic const word variable(SensorRaw, opcdSourceSensorRaw, kNumbOfTotalSensors, tSensors);

in RobotCIntrinsics.h to

intrinsic word variable(SensorRaw, opcdSourceSensorRaw, kNumbOfTotalSensors, tSensors);