A multiplexer is a device that has several digital or analog inputs and a single output. It forwards a given input to the output based on a separate set of digital inputs known as select lines. A multiplexer is often used to share a single data line when working with many inputs.
A demultiplexer acts as the multiplexer's counterpart. It has one input and many outputs essentially doing the opposite.
Usually these devices are used in pairs on both ends of the communication.
In software terms the multiplexer is nothing more than a case statement. It just redirects the proper input to the output. In this example I assume that the value of zero represents a missing value.
FUNCTION_BLOCK "MUX_4_TO_1_INT"
VERSION:1.0
VAR_INPUT
i0:INT; // input 0
i1:INT; // input 1
i2:INT; // input 2
i3:INT; // input 3
sel:INT; // input selector (0-3)
END_VAR
VAR_OUTPUT
out:INT; // output
END_VAR
BEGIN
case #sel of
0: #out := #i0; // redirect input 0
1: #out := #i1; // redirect input 1
2: #out := #i2; // redirect input 2
3: #out := #i3; // redirect input 3
else
#out := 0; // invalid selector. reset the output
end_case;
END_FUNCTION_BLOCK
The demultiplexer is pretty much the same but with reversed logic:
FUNCTION_BLOCK "DEMUX_1_TO_4_INT"
VERSION:1.0
VAR_INPUT
in :INT; // input
sel:INT; // output selector (0-3)
END_VAR
VAR_OUTPUT
q0:INT; // output 0
q1:INT; // output 1
q2:INT; // output 2
q3:INT; // output 3
END_VAR
BEGIN
#q0 := 0; // reset output 0
#q1 := 0; // reset output 1
#q2 := 0; // reset output 2
#q3 := 0; // reset output 3
case #sel of
0: #q0 := #in; // redirect to output 0
1: #q1 := #in; // redirect to output 1
2: #q2 := #in; // redirect to output 2
3: #q3 := #in; // redirect to output 3
end_case;
END_FUNCTION_BLOCK
Save these two scripts in the vault (don't forget to name the files after the blocks), open SCL editor and use them like any other FB.
FUNCTION_BLOCK "MAIN"
VERSION:1.0
VAR_INPUT
i0 : INT;
i1 : INT;
i2 : INT;
i3 : INT;
sel : INT;
END_VAR
VAR_OUTPUT
q0 : INT;
q1 : INT;
q2 : INT;
q3 : INT;
END_VAR
VAR
mux : "MUX_4_TO_1_INT"; // mux instance
demux : "DEMUX_1_TO_4_INT"; // demux instance
END_VAR
VAR_TEMP
data : INT;
END_VAR
BEGIN
// call the mux
#mux(i0:=#i0, i1:=#i1,
i2:=#i2, i3:=#i3,
sel:=#sel, out=>#data);
// call the demux
#demux(in:=#data, sel:=#sel,
q0=>#q0, q1=>#q1,
q2=>#q2, q3=>#q3);
END_FUNCTION_BLOCK
Really simple, isn't it? You can modify the code and add more inputs/outputs if needed.
You can also change the types. In the end it is just text that you can customize the way you need it to be.
Have a wonderful day!
Comments