Using arrays or bytes to set multiple outputs in Structured Text

3.3k views Asked by At

I am fooling around in TwinCAT3 trying and getting familiar with ST. I now have a simple question.

Say I have 8 LEDS. Each assigned to an output 1-8. Now I want to be able to send in a byte looking like such: 10101010. Lets call that variable to hold that byte setOUTPUTS. Would I initalize setOUTPUTS as follows to hold that?

bsetOUTPUTS := BYTE;  

After I initialize that variable, how could I loop through it to set each LED to the corresponding bit?

For instance: setOUTPUTS = 10001000, how would i loop through setOUTPUTS variable to set LED 8 and LED 4 ON , while leaving the others OFF.

IF this is not possible, what is the alternative way using arrays?

Thanks!!

3

There are 3 answers

3
pboedker On

You can compare each bit of your setOutputs variable with a bit that is shifted through the length of setOutputs:

FOR i := 0 TO 7 DO
  out[i] := setOutputs AND SHL(1, i);
END_FOR;
0
mrsargent On

To initialize a byte you would

setOUTPUTS : BYTE:=86; (* equiavlent to 01010101  *)

you can set the outputs based on a bit as follows

out1 := setOUTPUTS.0;  (* bit 0 of byte *)
out2:=setOUTPUTS.1;  (* bit 1 of byte *)

you might think that you could do something like to loop through the bits in the byte

FOR i:=0 TO 8 BY 1 DO
(* out is an array of outputs *)
out[i] := setOUTPUTS.i;
END_FOR

but unfortunately you are unable to do this. As far as I know setting them individually is the only way to accomplish this.

0
Stucky On

I would simply map the bit of "bsetOUTPUTS" to the IO.

enter image description here

Offset 0 means bit 0, offset 1 means bit 1, etc.

So I will link my channel 1 (LED 1) to bsetOUTPUTS offset 0, channel 2 to bsetOUTPUTS offset 1, etc.

enter image description here