How to simplify code using arrays and indexing

Introduction:

Within this post, we demonstrate how to read or write an array of data or index the device register referenced within a GetData or SetData statement. Adhering to these guidelines will allow you to produce more efficient code that is easier to maintain.

Software Version:

EasyBuilder Pro 6.03.02.463+

Instructions:

Note: This section is introduced under the assumption that you have already defined a GetData or SetData statement within a macro. To learn how to declare these functions, please review this post: Link.

Problem

  1. A simple macro, similar to what we’ve defined below is quite easy to write and maintain:
    Note: This macro retrieves device data from register 4x-1 and assigns it to a variable called “data”.

  2. A more complex macro or one that is longer in size can be quite hard to maintain and can easily lead to erroneous output:
    Note: This macro retrieves device data from register 4x-1 ~ 4x-30 and assigns it to data[0] ~ data[29]. There are a few errors below, can you spot them?

  3. When statements reference addresses that are not consecutive in nature, addressing in this form becomes even more complex:

Solution

  1. We can rewrite the macro within example 2 more efficiently by redefining what is referred to as the “data count”:
    Note: This will retrieve and transfer an array of data from 4x-1 ~ 4x-30 using a single line statement. the “data count” is defined as 30 which matches the array length.

  2. In some cases, you can rewrite the macro within example 3 more efficiently using a “For” loop with a counter variable ‘i’ to index the register number and array index:
    Note: The section “4x, 13 + (i * 13)” will jog the device address from 4x-13 to 4x-169 as ‘i’ increases. Similarly, the array index changes according to ‘i’.

Keywords

array, arrays, indexing, index, macro, getdata, setdata, function, functions, data, variable, statement, statements, for loop, loop, loops, code, simplify