You don't need 50 variables called Donut_01_Glazed through Donut_50_PleaseStopHelpMe. You need one box with numbered slots. That's an array.
You could declare ten separate variables. You could also juggle ten donuts on a unicycle. Both are bad ideas.
Donut_01_Glazed := 'Glazed';Donut_02_Sprinkle:= 'Sprinkle';Donut_03_Choco := 'Chocolate';Donut_04_Maple := 'Maple';Donut_05_Jelly := 'Jelly';Donut_06_Boston := 'Boston';Donut_07_Cruller := 'Cruller';Donut_08_OldFash := 'OldFashioned';Donut_09_Cinnamon:= 'Cinnamon';Donut_10_??? := 'help me';Now imagine looping through these. Go on. Imagine it. I'll wait.
VAR MyDonuts : ARRAY[0..9] OF STRING; END_VAR
One name. Numbered slots from [0] to [9]. You access any donut with MyDonuts[i]. Loops? Easy. Sanity? Restored.
Each slot has a number (the index) and can hold a value. Indices start at 0 because programmers like to keep you on your toes.
Click any slot to inspect it. Hit ✏️ Type to drop a new donut in.
Drag the slider to step through what happens when the PLC executes a single line of Structured Text. No CPUs were harmed in the making of this animation.
// One line. That's it. That's the lesson. MyDonuts[4] := 'Sprinkle';
MyDonuts[4]. "Slot 4, you're up."Here's the same donut box written as Structured Text, the kind of code you'd see in TwinCAT, CODESYS, Studio 5000, you name it. Change the index. Watch the PLC react.
(* === Declaration === *) VAR MyDonuts : ARRAY[0..9] OF STRING; i : INT := 3; currentItem : STRING; END_VAR (* === Fill the box at startup === *) MyDonuts[0] := 'Glazed'; MyDonuts[1] := 'Sprinkle'; MyDonuts[2] := 'Chocolate'; MyDonuts[3] := 'Maple'; MyDonuts[4] := 'Jelly'; MyDonuts[5] := 'Boston'; MyDonuts[6] := 'Cruller'; MyDonuts[7] := 'Old Fashioned'; MyDonuts[8] := 'Cinnamon'; MyDonuts[9] := 'Strawberry'; (* === Read whichever slot 'i' points at === *) currentItem := MyDonuts[i];
Type a number for i. The PLC will fetch MyDonuts[i]. Try -1 or 12. I dare you.
0 to 9 for an ARRAY[0..9]. Step outside and the PLC throws a tantrum.FOR i := 0 TO 9 DO HMI_Display[i] := MyDonuts[i]; END_FOR; // Ten lines of work? Nope. Three lines. You're welcome.
Three questions. Zero stakes. Maximum dignity.
MyDonuts : ARRAY[0..9] OF STRING;
One name. 10 numbered slots. Done.
MyDonuts[3] := 'Sprinkle';
Use := to stuff a value into a slot.
x := MyDonuts[3];
Same brackets, no := on the array side.
ARRAY[0..9] stops at 9. Not 10. 9.arr1. Name it MyDonuts and future-you will weep with gratitude.1 to 10. Loop from 0 to 9. (Or use UPPER_BOUND.)REAL in a STRING array. The type checker is watching. Always watching.