Legoboto: hajimemashou, LEGO MINDSTORMS NXT, sensor eventing

In the previous posts I offered some sample code for motor movement and dealing with sensors of the LEGO MINDSTORMS NXT product used with Bram Fokke's .NET API NXT#.

One important feature of the API was not covered before: Eventing

For each sensor you can register an event handler for when the data of the event handler changes. This implies that you poll the data from the sensor of course.

Here is the sample code:

using System;

using System.Collections.Generic;

using System.Text;

using Bram.NxtSharp;

 

namespace LegoNxtConsoleSample

{

    class Program

    {

        const string c_BluetoothComPort = "COM4";

 

 

        static void pressureSensorValueChangedEventHandler(NxtSensor sensor)

        {

            if (sensor is NxtPressureSensor)

            {

                NxtPressureSensor pressureSensor = (NxtPressureSensor)sensor;

                Console.Write("Pressure rawvalue:" + pressureSensor.RawValue + " means that sensor is ");

                if (pressureSensor.IsPressed)

                    Console.WriteLine("pressed");

                else

                    Console.WriteLine("not pressed");

            }

            else

            {

                Console.WriteLine("Problem: NxtPressureSensure expected but not received");

            }

        }

 

        static void SensorEventingDemo()

        {

            Console.WriteLine("pressure sensor eventing demo, running for 30 seconds");

            NxtBrick brick = new NxtBrick();

            brick.COMPortName = c_BluetoothComPort;

            brick.AutoPoll = true;

            NxtPressureSensor pressureSensor = new NxtPressureSensor();

            pressureSensor.AutoPoll = true;

            pressureSensor.AutoPollDelay = 50;

            pressureSensor.Brick = brick;

            brick.Sensor1 = pressureSensor;

            pressureSensor.ValueChanged += new SensorEvent(pressureSensorValueChangedEventHandler);

            //best practice: connect all sensors and motors first

            brick.Connect();

            System.Threading.Thread.Sleep(30000);

            brick.Disconnect();

        }

 

 

        static void Main(string[] args)

        {

            SensorEventingDemo();

        }

    }

}

 

 


Posted Apr 19 2007, 01:45 AM by Andreas Erben
developers.de is a .Net Community Blog powered by daenet GmbH.