LD UDFB Guided Learning Q06: – How is PLC-based numeric state machine similar a C case-switch?

This article is part of a guided learning series on building and analyzing User-Defined Function Blocks (UDFBs).

:pushpin: Canonical Article: Building a User-Defined Function Block (UDFB) Using Siemens TIA Portal
:blue_book: Learning Companion (Q&A): Explore All Questions

You are reading: Question 6

How is PLC-based numeric state machine similar a C case-switch statement?

Answer

The case-switch is a classic programming structure where an integer is used to select which portion of code is executed. Under the hood, we see a series of comparisons and jump statements. For example, is uiState equal to uiStOpen? Or uiStClosing? Or uiStClosed?

The same logic structure applies to the state machine. However, instead of performing a jump statement, each rung begins with a comparison of uiState to each possible enumerated state.

Tech Tip: Remember to use the break statement when programing a case-switch statement to prevent falling through to the next state. The PLC has a similar problem commonly associated with the β€œlast rung wins” logic error.

:writing_hand: Article by Aaron Dahlen, LCDR USCG (Ret.), Application Engineer at DigiKey