Introduction #
Implementing user-defined data structures and multi-dimensional arrays in Spin is different than it is in C/C++, Java, Python, PHP and other high-level languages. With a few special considerations, Spin can do this for larger software projects requiring complex data structures that need to be accessible via named fields. For example, to create an array of the following records in C/C++:
Record Format
byte name[ 33 ]
byte age
byte height
byte weight
// Make a simple type declaration such as:
struct typedef Person_typ
{
char name[ 32 ] ;
byte age;
byte height;
byte weight;
} Person;
// … Then instantiate an array Persons[] of these records with:
Person Persons[ NUM_RECORDS ];
This kind of programming pattern is very common. A “container” data structure is created then an array, list, file, etc. is built of the constituent data structures or records as a linear array.
Even to those not familiar with the C/C++ syntax above, it is clear that Person contains the fields of the desired record format. A simple dot or arrow operator in C/C++ can access these fields:
Persons[ 12 ].age = 25;
This assigns the value 25 to the age field in index 12 of the array.
The SPIN approach #
Achieving this is the kind of flexibility in Spin, with respect to user-defined data structures and types, that requires a few programming patterns and transformations:
- Multiple Arrays — This technique uses a multiple arrays where each array represents one field of the data structure. In other words, an array of n records where each record has m fields is transformed into m arrays of n elements each.
- Indexed Single Array — This technique uses a single array to hold records linearly in place much as the computer would internally store them, if the language supported user-defined data structures. With this format, an indexing scheme is used to access each record based on the prior knowledge of the size of each field in the record.
- External Object Array — This is the most advanced technique and the most robust of the three approaches. Spin allows not only external objects that are drivers and functional in nature, but also can use objects as actual data structures/containers. Additionally, Spin allows not only single objects to be declared, but also arrays of the same object, and then using the dot operator to access methods in those objects. This technique develops into a very object-oriented approach: user-defined data structures implemented as objects.
The application note AN003 available from OBEX illustrates the methodology and programming pattern of each approach with theory and a supporting demo program.