---
title: ".Net Micro Framework研究—带AD的模拟器"
author: "mmdev"
date: "2007-12-31T13:19:00Z"
tags: []
slug: "net-micro-framework-ad"
draft: false
lastmod: "2012-08-04T21:30:56Z"
id: 1620932
url: "https://mmdev.iteye.com/blog/1620932"
---

继昨天的研究，希望再接再厉把AD模入模出在模拟器上也实现出来，本以为挺简单，其实AD相关功能，与GPIO不同，在模拟器中前者通过GpioPort实现，后者通过SpiDevice实现。幸好有Temperature（温度采集）示例可以参考，否则一时真无法下手。不知道为什么，很简单的代码他们总写的很复杂，让你很难看懂，幸好有以前的相关的经验做底子，用了大半天的时间模入模出都搞定了。

下面就是模拟器中的AD输入输出的相关代码。

public class SpiADComponent : SpiDevice

{

public Int16 AW0 = 0;

public Int16 QW0 = 0;

protected override byte\[] Write(byte\[] data)

{

//------------

try

{

QW0 = (Int16)((data\[0] &lt;&lt; 8) + data\[1]);

}

catch { }

//------------

byte\[] bytes = new byte\[2];

bytes\[0] = (byte)(AW0 &gt;&gt; 8);

bytes\[1] = (byte)(AW0 & 0xff);

return bytes;

}

}

注：由于受西门子PLC200的影响比较大，所以把模拟量入和出，定义为AW0和QW0，并且用两个字节的整数表示，根据需要可以进行折算。

我们把昨天的GPIO代码稍加改进，把AD部分测试代码添加进去，代码如下：

static SPI \_spi;

public static void Main()

{

OutputPort\[] output = new OutputPort\[8];

InputPort\[] input = new InputPort\[8];

//叶帆模拟器GPIO的pin定义

Cpu.Pin\[] pin\_I = new Cpu.Pin\[8] { (Cpu.Pin)10, (Cpu.Pin)11, (Cpu.Pin)12, (Cpu.Pin)13, (Cpu.Pin)14,(Cpu.Pin)15, (Cpu.Pin)16, (Cpu.Pin)17 };

Cpu.Pin\[] pin\_Q = new Cpu.Pin\[8] { (Cpu.Pin)20, (Cpu.Pin)21, (Cpu.Pin)22, (Cpu.Pin)23, (Cpu.Pin)24, (Cpu.Pin)25, (Cpu.Pin)26, (Cpu.Pin)27 };

//SPI的pin定义

\_spi=new SPI(new SPI.Configuration((Cpu.Pin)30, true, 0, 0, false, false, 4000, SPI.SPI\_module.SPI1));

for (int i = 0; i &lt; 8; i++)

{

input\[i] = new InputPort(pin\_I\[i], false, Port.ResistorMode.PullDown);

output\[i] = new OutputPort(pin\_Q\[i], false);

}

int intNum = 0;

while (true)

{

output\[intNum].Write(!output\[intNum].Read());

Debug.Print(input\[0].Read().ToString() + " " + input\[1].Read().ToString() + " " + input\[2].Read().ToString() + " " + input\[3].Read().ToString() + " " + input\[4].Read().ToString()+ " " + input\[5].Read().ToString() + " " + input\[6].Read().ToString() + " " + input\[7].Read().ToString());

Debug.Print(ReadWriteAD((Int16)intNum).ToString() + " " + intNum.ToString());

if (++intNum &gt; 7) intNum = 0;

Thread.Sleep(1000);

}

}

public static Int16 ReadWriteAD(Int16 value)

{

byte\[] bout = new byte\[2];

byte\[] bin = new byte\[2];

bout\[0] = (byte)(value &gt;&gt; 8);

bout\[1] = (byte)(value & 0xff);

\_spi.WriteRead(bout, bin);

Int16 aw0=(Int16)((bin\[0] &lt;&lt; 8) + bin\[1]);

return aw0;

}

}

运行后的界面如下：

![](http://p.blog.csdn.net/images/p_blog_csdn_net/yefanqiu/MF07123101.jpg)

从上图可以看出，模拟器已经和测试程序进行交互了，即可以设置AW0的值，也可以获取QW0的值。

![](http://p.blog.csdn.net/images/p_blog_csdn_net/yefanqiu/MF07123102.jpg)

我又把模拟器改进了一下，可以支持多种IO模拟功能，目前已经完成了GPIO和AD，I2C应该也不难，但是Serial（串口）估计有问题，因为模拟器支持库没有相关函数。