ParallelOutputPort.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace UAM.InformatiX.SPOT.Hardware
{
public class ParallelOutputPort : IDisposable
{
OutputPort[] ports;
OutputPort ready;
InterruptPort busy;
Thread writeThread;

public ParallelOutputPort(Cpu.Pin[] pins) : this(pins, Cpu.Pin.GPIO_NONE, Cpu.Pin.GPIO_NONE) { }
public ParallelOutputPort(Cpu.Pin[] pins, Cpu.Pin dataReady) : this(pins, dataReady, Cpu.Pin.GPIO_NONE) { }
public ParallelOutputPort(Cpu.Pin[] pins, Cpu.Pin dataReady, Cpu.Pin busySignal)
{
ports = new OutputPort[pins.Length];
for (int i = 0; i < pins.Length; i++)
ports[i] = PortStore.GetOutput(pins[i]) /* ports[i] = new OutputPort(pins[i], false) */;

ready = dataReady == Cpu.Pin.GPIO_NONE ? null : PortStore.GetOutput(dataReady) /* new OutputPort(dataReady, false) */;
if (busySignal == Cpu.Pin.GPIO_NONE)
busy = null;
else
{
busy = new InterruptPort(busySignal, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth);
busy.OnInterrupt += new NativeEventHandler(OutputPort_OnBusyChanged);
}
}

void OutputPort_OnBusyChanged(uint port, uint state, TimeSpan time)
{
if (writeThread == null) return;

if (state != 0) writeThread.Suspend();
else writeThread.Resume();
}

public void Write(int value)
{
if (ready != null)
ready.Write(false);

for (int i = 0; i < ports.Length; i++)
{
ports[i].Write((value & 1) == 1);
value >>= 1;
}

if (ready != null)
ready.Write(true);

Thread.Sleep(1);
}
public void Write(int[] values)
{
writeThread = Thread.CurrentThread;
for (int i = 0; i < values.Length; i++)
Write(values[i]);
}
public void Write(byte[] values)
{
writeThread = Thread.CurrentThread;
for (int i = 0; i < values.Length; i++)
Write(values[i]);
}

public void Dispose()
{
if (busy != null) busy.Dispose();
if (ready != null) ready.Dispose();
}
}
}