点亮了LED后,都会想怎么把它闪烁起来。要闪烁自然要用到延时,先上代码
while (true)
{
led0.Write(!led0.Read());
Thread.Sleep(500);
}
led0.Write就是直接写PB5的电平,led0.Read()是读现在PB5电平状态,连接起来就是翻转PB5的电平,达成led0的闪烁。 Thread.Sleep(500)自然就是延时函数,这里MF只提供了以ms为单位的延时(很多人就会想,如果操作GPIO需要us级的延时话,怎么办,这里MF是无能为力,目前的解决方法是在底层来操作,然后给上面接口来直接使用,其实这里也是移植最大的难度,我也还没有开始折腾,能力还有限啊)。VS也会指示 Thread.Sleep有错误,跟前面一样,在代码开头加using System.Threading;。然后调试,就可以看到led0按1HZ的频率闪烁起来了,So easy!
再看初始化,PB5为(Cpu.Pin)21,这也太难记,有什么方法把它改成PB5这种,C#这么高级语言,自然是没什么问题,像用C的宏定义一样来做就要可以了。这里我也写了一个类文件 :
amespace MFPins
{
public class CPU
{
public static class Pins
{
public const Cpu.Pin PA0 = (Cpu.Pin)0;
public const Cpu.Pin PA1 = (Cpu.Pin)1;
public const Cpu.Pin PA2 = (Cpu.Pin)2;
public const Cpu.Pin PA3 = (Cpu.Pin)3;
public const Cpu.Pin PA4 = (Cpu.Pin)4;
public const Cpu.Pin PA5 = (Cpu.Pin)5;
public const Cpu.Pin PA6 = (Cpu.Pin)6;
public const Cpu.Pin PA7 = (Cpu.Pin)7;
public const Cpu.Pin PA8 = (Cpu.Pin)8;
public const Cpu.Pin PA9 = (Cpu.Pin)9;
public const Cpu.Pin PA10 = (Cpu.Pin)10;
public const Cpu.Pin PA11 = (Cpu.Pin)11;
public const Cpu.Pin PA12 = (Cpu.Pin)12;
public const Cpu.Pin PA13 = (Cpu.Pin)13;
public const Cpu.Pin PA14 = (Cpu.Pin)14;
public const Cpu.Pin PA15 = (Cpu.Pin)15;
public const Cpu.Pin PB0 = (Cpu.Pin)16;
public const Cpu.Pin PB1 = (Cpu.Pin)17;
public const Cpu.Pin PB2 = (Cpu.Pin)18;
public const Cpu.Pin PB3 = (Cpu.Pin)19;
public const Cpu.Pin PB4 = (Cpu.Pin)20;
public const Cpu.Pin PB5 = (Cpu.Pin)21;
public const Cpu.Pin PB6 = (Cpu.Pin)22;
public const Cpu.Pin PB7 = (Cpu.Pin)23;
只贴这么多,剩下的自行补齐就可以了。那么初始化就变 OutputPort led0 = new OutputPort(MFPins.CPU.Pins.PB5, false);这样就明朗多了。然后把led1也加进去,就可以做流水灯了,这里直接贴代码整个代码:
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using System.Threading;
using MFPins;
namespace LED
{
public class Program
{
public static void Main()
{
OutputPort led0 = new OutputPort(MFPins.CPU.Pins.PB5, true);
OutputPort led1 = new OutputPort(MFPins.CPU.Pins.PE5, true);
while (true)
{
led0.Write(!led0.Read());
Thread.Sleep(500);
led1.Write(!led1.Read());
}
}
}
}
按F5调试,看到led0跟led1红绿交替闪烁,心情真是太愉悦了。哈哈!后面附上整个工程,还有固件也有更新,我在写led1的时候,发现led1没闪烁,最后是找到固件那边GPIOE没有初始化(led1用到PE5,固件只初始化了A、B、C三个端口)。