This article is part of a guided learning series on building and analyzing User-Defined Function Blocks (UDFBs).
Canonical Article: Building a User-Defined Function Block (UDFB) Using Siemens TIA Portal
Learning Companion (Q&A): Explore All Questions
You are reading: Question 12
Should we use unsigned int of double as the state variable?
Clarification
The featured example uses an unsigned integer as the state variable. What range of number may be held in an unsigned integer and is this excessive for this application?
- USINT: 0–255
- UINT: 0–65,535
- UDINT: 0–4,294,967,295
Answer
The unsigned integer is a 16-bit value allowing up to 65,536 (zero-indexed) unique states. This is clearly excessive for all but the largest state machines running on equally capable hardware.
The next viable alternative is 8-bit unsigned short integer allowing up to 256 unique states. In theory, this would save memory for both the state variables and the constants used to identify each state (e.g., usiStateFault). As an alternative, we could move in the opposite direction and use a double integer for 4,294,967,297 unique states.
While we do not know the underlying hardware architecture or code structure for the S7-1200, we can speculate that the S7-1200 is built upon a modern 32-bit core. Consequently, we can expect the operations, including those with 8-bit variables, to be performed by the CPU in 32-bit units.
With that said, there is little advantage to using short or even unsigned integers. In fact, to prevent errors there is a pragmatic argument for promoting all calculation to unsigned double integers.
Article by Aaron Dahlen, LCDR USCG (Ret.), Application Engineer at DigiKey