Compass application


Inspired by these two cool videos on YouTube: here and here.

Assumes a NXT robot configuration alike the TriBot,
and a HiTecnic compass sensor attached to port 4.



Usage

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using NKH.MindSqualls;

namespace NxtCompass1
{
    public partial class Form1: Form
    {
        private NxtBrick brick;
        private NxtMotorSync motorPair;
        private HiTechnicCompassSensor compassSensor;

        public Form1()
        {
            InitializeComponent();

            this.Text = "Disconnected";
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                byte comPort = byte.Parse(this.txtComPort.Text);
                brick = new NxtBrick(comPort);

                brick.MotorB = new NxtMotor();
                brick.MotorC = new NxtMotor();
                motorPair = new NxtMotorSync(brick.MotorB, brick.MotorC);

                compassSensor = new HiTechnicCompassSensor();
                brick.Sensor4 = compassSensor;

                compassSensor.PollInterval = 50;
                compassSensor.OnPolled += new Polled(compassSensor_OnPolled);

                brick.Connect();

                this.Text = "Connected: " + brick.Name;
            }
            catch
            {
                Disconnect();
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            Disconnect();
        }

        private void Idle()
        {
            if (brick != null && brick.IsConnected)
                motorPair.Idle();
        }

        private void Disconnect()
        {
            Idle();
            System.Threading.Thread.Sleep(1000);

            if (brick != null && brick.IsConnected)
                brick.Disconnect();

            brick = null;
            motorPair = null;

            this.Text = "Disconnected";
        }

        void compassSensor_OnPolled(NxtPollable polledItem)
        {
            Int16 heading = compassSensor.Heading;

            sbyte turnRatio = (sbyte) ((heading > 180) ? 100 : -100);

            sbyte power = (sbyte) Math.Min(100, 180 - Math.Abs(heading - 180));

            motorPair.Run(power, 0, turnRatio);
        }
    }
}

Have a closer look at the compassSensor_OnPolled eventhandler. It is the one that does the trick.

Download

NxtCompass1.zip


http://www.mindsqualls.net