跳到主要内容

GPIO 与中断

用 OutputPort 点灯、用 InterruptPort 读按键并注册外部中断。板级引脚名调用 快速开始 里的 Mainboard.Pins,不要写裸引脚号。

完整示例​

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using YFSoft.Hardware.LxRouterII;

namespace GpioDemo
{
public class Program
{
static OutputPort s_userLed;
static OutputPort s_commLed;
static int s_presses;

public static void Main()
{
s_userLed = new OutputPort(Mainboard.Pins.UserLED, false);
s_commLed = new OutputPort(Mainboard.Pins.CommLED, false);

InterruptPort key = new InterruptPort(
Mainboard.Pins.Button, true,
Port.ResistorMode.Disabled,
Port.InterruptMode.InterruptEdgeBoth);
key.OnInterrupt += new NativeEventHandler(OnKey);

while (true)
{
s_commLed.Write(!s_commLed.Read()); // 500 ms 心跳
Thread.Sleep(500);
}
}

static void OnKey(uint data1, uint data2, DateTime time)
{
s_presses++;
s_userLed.Write(!s_userLed.Read());
Debug.Print("KEY pin=" + data1 + " state=" + data2
+ " presses=" + s_presses);
}
}
}

编译结果(实测):.pe 1.1 KB。OnInterrupt 回调里 data1 是引脚号,data2 是该次跳变的电平(按下 0 / 松开 1)。

必须知道的三个细节​

① 委托要能被 GC 看到。 key.OnInterrupt += new NativeEventHandler(OnKey) 里的委托如果没有被静态字段或长生命周期对象持有,GC 可能把它回收,表现为「按了几次之后就再也不响应」。上面的写法把 key 放在 Main 的局部变量里,是靠 Main 的栈帧一直活着才没出事——生产代码请把它提到 static 字段。

② 机械按键需要软件消抖。 InterruptPort 的第二个参数 true 会启用 glitch filter,但对劣质按键仍可能连发多次中断。要求严格计数的场合,在回调里按时间戳做 20~50 ms 去重。

③ 中断回调里不要做耗时操作。 OnInterrupt 跑在中断上下文,里面 Thread.Sleep、开 Socket、读大文件都可能拖住整个调度。正确做法是回调里只置标志或入队,主线程轮询处理。

跨页提醒:RS-485 总线电源​

凌霄 II 的 RS-485 收发器由 PC6(Mainboard.Pins.PB_EN) 控制,低电平关断。不拉高就去收数据,现象是「发得出去、一个字节也收不到」,很容易误判成波特率或接线问题。详见 串口与 RS-485。