In my previous post I was writing about MultiOutputPort class, which outputs byte values to pins joined together. This post is about reading byte values from joined pins in .NET Micro Framework.
MultiInputPort class
Constructor for MultiInputPort class is similar to MultiOutputPort. First argument is array of Cpu.Pin that represents bits of input value. First member of the array is the least significant bit of the value read. Second argument enables glitch filter. Last argument specifies the resistor mode for input pins.
/// <summary>
/// Join multiple pins to read numbers
/// </summary>
public class MultiInputPort : IDisposable
{
/// <summary>
/// Creates new MultiInputPort object
/// </summary>
/// <param name="portList">Array of Cpu.Pin port. Least signigicant bit is first</param>
/// <param name="glitchFilter">Glitch filter</param>
/// <param name="resistorMode">Resistor mode</param>
public MultiInputPort(Cpu.Pin[] portList, bool glitchFilter, Port.ResistorMode resistorMode)
{
// Argument validation
if (portList == null || portList.Length == 0)
throw new ArgumentOutOfRangeException();
// Saving performance. Do not repeat query for array length
int portListLength = portList.Length;
// Create array of InputPorts
this._portList = new InputPort[portListLength];
for (int i = 0; i < portListLength; i++)
{
this._portList[i] = new InputPort(portList[i], glitchFilter, resistorMode);
}
}
/// <summary>
/// Reads a value from the input output
/// </summary>
/// <returns>Number value</returns>
public int Read()
{
int inputValue = 0;
for (int i = this._portList.Length - 1; i >= 0; i--)
{
inputValue <<= 1;
if (this._portList[i].Read())
inputValue |= 0x01;
}
return inputValue;
}
#region IDisposable Members
public void Dispose()
{
// Dispose array members
int portListLength = this._portList.Length;
for (int i = 0; i < portListLength; i++)
{
this._portList[i].Dispose();
}
}
#endregion
/// <summary>
/// InputPort array
/// Least significant bit is fisrt
/// </summary>
private InputPort[] _portList;
}
Not limited to bytes
Since the input pins are set as an array, the input value could not be necessary byte. It can be nibble (4 bits), short or even int. Example of using this class follows.
MultiInputPort port = new MultiInputPort(new Cpu.Pin[8] {
Cpu.Pin.GPIO_Pin0,
Cpu.Pin.GPIO_Pin1,
Cpu.Pin.GPIO_Pin2,
Cpu.Pin.GPIO_Pin3,
Cpu.Pin.GPIO_Pin4,
Cpu.Pin.GPIO_Pin5,
Cpu.Pin.GPIO_Pin6,
Cpu.Pin.GPIO_Pin7}, false, Port.ResistorMode.PullUp);
int data = port.Read();