Sysmac Studio · NJ/NX · IEC 61131-3

The donut box

An array is one name with many numbered slots, and on an Omron controller it is the tidiest way to hold a row of the same thing. Here you fill a box of donuts and watch what the variables do as you go.

🍩 ARRAY[0..9] OF Donut ~10 min
01 · The problem

Ten donuts, ten lonely variables?

The messy way: one variable each

donut0 : BOOL; donut1 : BOOL; donut2 : BOOL; donut3 : BOOL; donut4 : BOOL; … donut9

That's ten separate variables. You can't loop over them, and an eleventh donut means typing another line by hand, which gets old quickly as the count grows.

The array way: one declaration

donuts : ARRAY[0..9] OF BOOL;

That one line gives you a box of 10 numbered slots, indices 0 to 9. You reach any slot by its number, as in donuts[3], and a FOR loop can walk through all of them in a few lines.

💡 Sysmac note: Omron NJ/NX arrays start at index 0 by default, so ARRAY[0..9] gives you exactly 10 slots. You can pick any range you like ([1..10], [-5..5]), but 0-based is the house style.

02 · Play

Fill the box

Click a slot to select it, then store a donut or clear it. The Structured Text on the right is exactly what you'd type in Sysmac Studio to do the same thing.

Selected: none 0 / 10 filled

Live Structured Text

// click a slot…
donuts := box of 10 BOOLs
select a slot to inspect it
03 · Indexing

Reach in by number

The index in the square brackets is a number, and it can also be a variable. This is where arrays earn their keep: change i and the same line of code reaches a different slot.

donuts[3]
pick an index and press Read

⚠️ Reach past the end, say with donuts[10], and Sysmac Studio flags an out-of-range access. The box has slots 0..9; there is no slot 10.

04 · The payoff

Count them with one loop

count := 0;
FOR i := 0 TO 9 DO
  IF donuts[i] THEN
    count := count + 1;
  END_IF;
END_FOR;

One loop walks every slot, no matter how big the box. Run it against the box you filled above:

press Run to count the donuts you stored
05 · Check yourself

One quick question

In donuts : ARRAY[0..9] OF BOOL;, how many slots are there, and what's the last valid index?