Overview
This tutorial demonstrates how to handle events with a Netduino board. Event handling is a pattern commonly used with Windows based programming. However, it can be used without a Windowing technology.
Event handling is nothing more than reacting to a given situation. Such as a button being pressed. It hides a lot of the ugly code that may be required to POLL or LISTEN in order to accomplish this task.
Code Sample
using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace EventHandlingExample
{
public class Program
{
static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);
public static void Main()
{
// write your code here
InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);
Thread.Sleep(Timeout.Infinite);
}
static void button_OnInterrupt(uint data1, uint data2, DateTime time)
{
led.Write(data2 == 0);
}
}
}
Details
The code show basically creates a button (i.e. InterruptPort) and attaches an event to the button. There is a method defined which handles the event called button_OnInterrupt(..). This method does nothing more than write to an LED. It can actually do anything you like and does not need to blink an LED.
Video Tutorial
The following video is brought to you buy Secret Labs. They have created a nifty video which shows you all the details and lays it out in great detail.