ASCIMathML.js

Sunday 15 January 2012

Digital IO Using Interupt Events

The previous post showed that we can read the value of D0 by connecting it to D1, setting D1 as an InputPort and using the Read() method.  Whilst this is find for a Hello World demo proving that it works, it's not much good for the real world.  What if we want D1 to report when the value changes?

For this we need to use the InteruptPort, and the OnInterupt event.  Even though the InputPort exposes this event, when you try to wire it up the framework throws one of its ever useful InvalidOperation exceptions.

So, we've got the Netduino wired up just like before, with D0 connected directly to D1, as so:

Pin D0 connected to pin D1

The code for our sample program is then:

namespace DigitalIOHelloWorld
{
    public class Program
    {
        public static void Main()
        {
            OutputPort pinD0 = new OutputPort(Pins.GPIO_PIN_D0, false);
            InterruptPort pinD1 = new InterruptPort(Pins.GPIO_PIN_D1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
            pinD1.OnInterrupt += new NativeEventHandler(pinD1_OnInterrupt);
            while (true)
            {
                Thread.Sleep(1000);
                Debug.Print("D0 = " + pinD0.Read());
                pinD0.Write(true);
                Thread.Sleep(1000);
                Debug.Print("D0 = " + pinD0.Read());
                pinD0.Write(false);
                Debug.Print("Reading D1 = " + pinD1.Read());
            }
        }

        static void pinD1_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            Debug.Print("D1: data1 = " + data1 + "\tdata2 = " + data2 + "\ttime = " + time.ToLocalTime());
        }
    }
}


Now, when the input signal to D1 changes (i.e. when the output from D0 changes) the event is triggered and the Debug statement prints this out.  We can see it's working as every time the we change the D0 output, we see the new state of D1.


The statement gives us three pieces of information.  Look at data2 now though, a value of 1 means that the voltage is high, 0 means it is low.

The Debug information appears in the Output Window, and will look like this:

D0 = False
Turning D0 on
Reading D1 = True
D1: data1 = 28    data2 = 1    time = 01/01/2009 00:13:24
D0 = True
Turning D0 off
Reading D1 = False
D1: data1 = 28    data2 = 0    time = 01/01/2009 00:13:25
D0 = False
Turning D0 on
Reading D1 = True
D1: data1 = 28    data2 = 1    time = 01/01/2009 00:13:26

No comments:

Post a Comment