Netduino 2 オンボードLEDのボタン動作2 [InterruptPort]

Netduino 2 (Visual Studio 2015 C#) のオンボードLED点灯の動作検証をしています。

 

Visual Studio 2015 C# のソース記述

AdvancedButtonApp

 

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;

namespace AdvancedButtonApp
{
    public class Program
    {
        // オンボードLED
        static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

        public static void Main()
        {
            // write your code here

            // オンボードボタン
            InterruptPort button = new InterruptPort(Pins.ONBOARD_BTN, false, Port.ResistorMode.
              Disabled, Port.InterruptMode.InterruptEdgeBoth);

            button.OnInterrupt += Button_OnInterrupt;

            Thread.Sleep(Timeout.Infinite);

        }

        private static void Button_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            led.Write(data2 == 0);
        }
    }
}

上記の説明

補足1

InterruptPort はデバイスのデータを入力するためのポートです。

と言うと、「InputPort との違いは何?」という疑問がわくと思います。
InterruptPort の特徴は、入力値の H / L が切り替わったタイミングでイベントを発行してくれる点です。
コンストラクターの引数によって、H→L、L→H、またはその両方でイベントを投げてくれるように指定できます。
InputPort は定期的にセンサーデータを読み出したい場合に使用し、InterruptPort は必要なデータが得られるタイミングが不定期な場合に使用するといいと思います。

 

補足2
例えば、定期的に室温を測定したい場合は InputPort を使い、周囲の温度が何度以上になったら何かアクションが必要な場合は InterruptPort を使うなどの使い分けです。
前回、ボタンのオンオフを InputPort を使って紹介しましたが、ボタンについては実は今回の InterruptPort のほうが適することが多いです。

 

常時観測するのでなく割り込み駆動になります。
OnInterruptで指定した関数が割り込みで飛んでくるのですが
OnInterrupt(uint port, uint state, TimeSpan time)
という引数になるようなので、状態は第二引数にかえってくるので
{
     led.Write(data2 == 0);
}
だと
data2が0のときTrueなのでH
それ以外の場合はFalseなのでL
になり、結果、スイッチとLEDは反転挙動になるとおもいます。

 

一般的な記述は、Stack Overflowに記述されている通りになるようです。

How do I implement interrupt in micro framework?

 

まだまだC#を習得している初心者ですので説明不足で済みません。

ご了承願います。

iOSと同じようにDelegateがあることが知りましたのでメモとして記述しておきます。

どう説明したら良いかは済みませんが出来ませんのでご了承願います。

まだまだC#を習得している初心者です。

 

NativeEventHandler Delegate

A multicast (combinable) delegate that defines the event handler for a native event.

Namespace: Microsoft.SPOT.Hardware
Assembly: Microsoft.SPOT.Hardware (in microsoft.spot.hardware.dll)

 

C#

public delegate void NativeEventHandler (
         UInt32 data1,
         UInt32 data2,
         TimeSpan time
)

Parameters

data1First parameter (can be the port).data2Second parameter (can be the state).timeTime of the event.

 

目 次