Bird
Raised Fist0
PLC Programmingscripting~15 mins

Function block definition in PLC Programming - Deep Dive

Choose your learning style10 modes available
Overview - Function block definition
What is it?
A function block is a reusable piece of code in PLC programming that groups inputs, outputs, and internal logic together. It acts like a mini-program with its own memory, allowing you to create complex control functions. You define a function block once and then use it many times in your program. This helps organize and simplify automation tasks.
Why it matters
Without function blocks, PLC programs would be long, repetitive, and hard to manage. Function blocks let you reuse tested code, reduce errors, and make your programs easier to understand and maintain. This saves time and improves reliability in controlling machines and processes.
Where it fits
Before learning function blocks, you should understand basic PLC programming concepts like variables, inputs/outputs, and simple instructions. After mastering function blocks, you can learn about advanced topics like function block instances, state machines, and structured text programming.
Mental Model
Core Idea
A function block is a self-contained unit of logic with inputs, outputs, and memory that you can reuse like a machine part in your PLC program.
Think of it like...
Think of a function block like a coffee machine: you put in water and coffee grounds (inputs), press a button (trigger), and it gives you coffee (output). The machine remembers settings like strength or temperature (internal memory) for next time.
┌───────────────────────────┐
│       Function Block      │
│ ┌───────┐   ┌───────────┐ │
│ │Inputs │→→│  Logic    │→→│Outputs│
│ └───────┘   └───────────┘ │
│        ↑ Internal Memory   │
└───────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a Function Block
🤔
Concept: Introduce the basic idea of a function block as a reusable code unit with inputs and outputs.
In PLC programming, a function block groups inputs, outputs, and internal logic into one unit. It is like a small program you can use multiple times. For example, a timer function block takes a time input and outputs a signal after that time passes.
Result
You understand that function blocks package logic and data together for reuse.
Understanding that function blocks combine data and behavior helps you see how PLC programs stay organized and modular.
2
FoundationInputs, Outputs, and Internal Variables
🤔
Concept: Explain the three main parts of a function block: inputs, outputs, and internal memory.
Inputs are values you give to the function block, like sensor readings. Outputs are results the block sends out, like turning on a motor. Internal variables store information inside the block between calls, like remembering a timer count.
Result
You can identify and separate inputs, outputs, and internal data in a function block.
Knowing these parts clarifies how function blocks keep track of state and interact with the outside world.
3
IntermediateDefining a Simple Function Block
🤔Before reading on: do you think a function block can have code that runs every time it is called or only once? Commit to your answer.
Concept: Show how to write a basic function block with inputs, outputs, and logic.
Example in IEC 61131-3 Structured Text: FUNCTION_BLOCK FB_Timer VAR_INPUT IN : BOOL; PT : TIME; END_VAR VAR_OUTPUT Q : BOOL; END_VAR VAR ET : TIME; END_VAR // Logic: if IN is true, start counting time IF IN THEN ET := ET + T#100ms; // increment elapsed time IF ET >= PT THEN Q := TRUE; ELSE Q := FALSE; END_IF ELSE ET := T#0s; Q := FALSE; END_IF END_FUNCTION_BLOCK
Result
You see how inputs control behavior, outputs reflect status, and internal variables keep track of time.
Understanding that function blocks run their code repeatedly and maintain state explains how they model real-world devices.
4
IntermediateUsing Function Block Instances
🤔Before reading on: do you think multiple instances of the same function block share memory or have separate memory? Commit to your answer.
Concept: Explain how to create and use multiple independent copies of a function block in a program.
Each time you use a function block, you create an instance with its own memory. For example: VAR Timer1 : FB_Timer; Timer2 : FB_Timer; END_VAR Timer1(IN := TRUE, PT := T#5s); Timer2(IN := FALSE, PT := T#10s); Each timer counts independently because they have separate internal variables.
Result
You understand that instances allow reuse without interference between copies.
Knowing that each instance keeps its own state prevents bugs caused by shared memory in automation programs.
5
IntermediateFunction Block Interfaces and Encapsulation
🤔
Concept: Introduce the idea that function blocks hide internal details and expose only inputs and outputs.
Function blocks act like black boxes: you only interact with inputs and outputs. Internal variables are hidden, so you cannot change them directly. This protects the logic and prevents accidental errors.
Result
You appreciate how encapsulation improves program safety and clarity.
Understanding encapsulation helps you design reliable and maintainable automation systems.
6
AdvancedStateful Behavior in Function Blocks
🤔Before reading on: do you think function blocks can remember past events to change future outputs? Commit to your answer.
Concept: Explain how internal memory allows function blocks to behave differently based on history or previous inputs.
Function blocks can store information like counters or flags inside internal variables. For example, a latch block remembers if it was turned on before and keeps output true even if input goes false. This lets you model complex control logic that depends on past events.
Result
You see how function blocks can implement memory and state machines.
Knowing that function blocks keep state unlocks powerful control patterns beyond simple input-output mapping.
7
ExpertOptimizing Function Block Performance and Memory
🤔Before reading on: do you think all function block instances consume the same memory regardless of usage? Commit to your answer.
Concept: Discuss how function blocks use memory and CPU cycles, and how to write efficient blocks for large systems.
Each function block instance uses memory for inputs, outputs, and internal variables. Complex blocks with many variables or timers consume more resources. Efficient design minimizes unnecessary variables and uses local variables inside methods. Also, avoid heavy computations inside blocks called very often to keep CPU load low.
Result
You understand how to balance functionality and resource use in real PLC projects.
Knowing resource costs helps you write scalable automation programs that run smoothly on limited hardware.
Under the Hood
Function blocks are compiled into code that runs cyclically in the PLC scan cycle. Each instance has its own memory area storing inputs, outputs, and internal variables. During each scan, the PLC calls the function block code, passing current inputs and updating outputs. Internal variables preserve their values between scans, enabling stateful behavior.
Why designed this way?
Function blocks were designed to modularize control logic and enable reuse with independent state. Early PLCs had limited memory and processing power, so encapsulating logic with clear interfaces helped manage complexity. Alternatives like global variables or inline code made programs hard to maintain and error-prone.
┌───────────────┐       ┌───────────────┐
│ PLC Scan Loop │──────▶│ Function Block│
│               │       │   Instance    │
│  Inputs Data  │──────▶│  Inputs (IN)  │
│               │       │  Internal Var │
│               │       │  Outputs (Q)  │
│               │◀──────│               │
│ Outputs Data  │       └───────────────┘
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do multiple instances of the same function block share internal memory? Commit to yes or no.
Common Belief:All instances of a function block share the same internal variables and memory.
Tap to reveal reality
Reality:Each instance of a function block has its own separate memory and internal variables.
Why it matters:Believing instances share memory can cause confusion and bugs when different parts of the program unexpectedly affect each other.
Quick: Does a function block run its code only once or every PLC scan? Commit to your answer.
Common Belief:Function blocks execute their code only once when called or triggered.
Tap to reveal reality
Reality:Function blocks run their code every PLC scan cycle, updating outputs based on current inputs and internal state.
Why it matters:Thinking function blocks run once leads to incorrect assumptions about timing and state updates, causing logic errors.
Quick: Can you directly change internal variables of a function block from outside? Commit to yes or no.
Common Belief:You can access and modify internal variables of a function block directly from the main program.
Tap to reveal reality
Reality:Internal variables are private to the function block and cannot be changed directly from outside; only inputs and outputs are accessible.
Why it matters:Trying to modify internal variables breaks encapsulation and can cause unpredictable behavior or program crashes.
Quick: Are function blocks only useful for simple tasks? Commit to yes or no.
Common Belief:Function blocks are only for simple, small tasks like timers or counters.
Tap to reveal reality
Reality:Function blocks can implement very complex logic, including state machines, communication protocols, and entire subsystems.
Why it matters:Underestimating function blocks limits your ability to design scalable and maintainable automation systems.
Expert Zone
1
Function blocks can be nested inside other function blocks, enabling hierarchical design patterns that mirror real-world systems.
2
The order of execution of function block instances can affect program behavior, especially when outputs feed inputs of other blocks; understanding scan order is critical.
3
Some PLC platforms optimize function blocks by sharing code but keeping separate data, reducing memory footprint without losing instance independence.
When NOT to use
Avoid using function blocks for purely combinational logic that does not require memory; simple functions or inline code are more efficient. Also, for very high-speed or time-critical tasks, consider using specialized instructions or hardware modules instead.
Production Patterns
In real-world systems, function blocks are used to model physical devices like motors, valves, and sensors. They often implement state machines for modes like start, run, stop. Large projects use libraries of tested function blocks to ensure consistency and reduce development time.
Connections
Object-Oriented Programming (OOP)
Function blocks are similar to classes in OOP, encapsulating data and behavior.
Understanding function blocks as OOP-like units helps bridge PLC programming with software engineering principles.
State Machines
Function blocks often implement state machines to manage complex control sequences.
Knowing how function blocks maintain state clarifies how to design reliable automation workflows.
Electrical Relay Logic
Function blocks abstract and replace traditional relay logic with programmable control.
Recognizing this connection helps electricians and engineers transition from hardware to software control.
Common Pitfalls
#1Using one function block instance for multiple independent tasks.
Wrong approach:VAR Timer : FB_Timer; END_VAR // Using Timer for two different timers Timer(IN := Start1, PT := T#5s); Timer(IN := Start2, PT := T#10s);
Correct approach:VAR Timer1 : FB_Timer; Timer2 : FB_Timer; END_VAR Timer1(IN := Start1, PT := T#5s); Timer2(IN := Start2, PT := T#10s);
Root cause:Misunderstanding that one instance cannot track multiple independent states.
#2Trying to access or modify internal variables of a function block directly.
Wrong approach:Timer.ET := T#0s; // Reset internal elapsed time directly
Correct approach:Use inputs or methods provided by the function block to control behavior, e.g., Timer(IN := FALSE);
Root cause:Not respecting encapsulation and private data boundaries.
#3Assuming function block code runs only once or on trigger.
Wrong approach:Expecting output to update only when input changes, ignoring scan cycle behavior.
Correct approach:Design logic knowing function blocks execute every scan, updating outputs continuously.
Root cause:Lack of understanding of PLC scan cycle and execution model.
Key Takeaways
Function blocks are modular, reusable units combining inputs, outputs, and internal memory to model control logic.
Each function block instance has its own memory, allowing multiple independent copies in a program.
Function blocks run their code every PLC scan, maintaining state between scans for complex behaviors.
Encapsulation protects internal variables, exposing only inputs and outputs to the rest of the program.
Understanding function blocks bridges PLC programming with software engineering concepts like objects and state machines.

Practice

(1/5)
1. What is the main purpose of a Function Block in PLC programming?
easy
A. To group inputs, outputs, and code for repeated tasks
B. To store data permanently in the PLC
C. To create a graphical user interface
D. To connect the PLC to external devices

Solution

  1. Step 1: Understand the role of function blocks

    Function blocks group inputs, outputs, and code to perform tasks repeatedly in PLC programs.
  2. Step 2: Compare options with the definition

    Only To group inputs, outputs, and code for repeated tasks describes grouping inputs, outputs, and code for reuse, which matches the function block purpose.
  3. Final Answer:

    To group inputs, outputs, and code for repeated tasks -> Option A
  4. Quick Check:

    Function block purpose = Group inputs, outputs, and code [OK]
Hint: Function blocks bundle inputs, outputs, and code for reuse [OK]
Common Mistakes:
  • Confusing function blocks with data storage
  • Thinking function blocks create user interfaces
  • Assuming function blocks connect hardware directly
2. Which of the following is the correct way to start defining a function block named MotorControl in IEC 61131-3 structured text?
easy
A. PROGRAM MotorControl
B. FUNCTION MotorControl
C. VAR MotorControl
D. FUNCTION_BLOCK MotorControl

Solution

  1. Step 1: Recall syntax for function block definition

    In IEC 61131-3, function blocks start with the keyword FUNCTION_BLOCK followed by the name.
  2. Step 2: Check each option

    FUNCTION_BLOCK MotorControl uses FUNCTION_BLOCK MotorControl, which is correct. Options A, B, and D use other keywords for different constructs.
  3. Final Answer:

    FUNCTION_BLOCK MotorControl -> Option D
  4. Quick Check:

    Function block syntax = FUNCTION_BLOCK Name [OK]
Hint: Function blocks start with FUNCTION_BLOCK keyword [OK]
Common Mistakes:
  • Using FUNCTION instead of FUNCTION_BLOCK
  • Confusing PROGRAM with function block
  • Using VAR keyword to define function blocks
3. Given this function block code snippet, what will be the output of FB1.Output after calling FB1.Run() twice?
FUNCTION_BLOCK FB1
VAR_INPUT
  In: BOOL;
END_VAR
VAR_OUTPUT
  Output: INT;
END_VAR
VAR
  Counter: INT := 0;
END_VAR

METHOD PUBLIC Run
IF In THEN
  Counter := Counter + 1;
END_IF
Output := Counter;
END_METHOD

END_FUNCTION_BLOCK

// Usage:
FB1.In := TRUE;
FB1.Run();
FB1.Run();
medium
A. 2
B. 1
C. 0
D. TRUE

Solution

  1. Step 1: Understand the counter increment logic

    Each call to Run checks if In is TRUE, then increments Counter by 1.
  2. Step 2: Trace two calls with In = TRUE

    First call increments Counter from 0 to 1, second call increments from 1 to 2. Output is set to Counter.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Counter increments twice with In=TRUE = 2 [OK]
Hint: Count increments each Run call if input TRUE [OK]
Common Mistakes:
  • Assuming Output resets each call
  • Confusing BOOL and INT output types
  • Forgetting Counter is retained between calls
4. Identify the error in this function block definition:
FUNCTION_BLOCK FB_Error
VAR_INPUT
  Start: BOOL;
END_VAR
VAR_OUTPUT
  Status: BOOL;
END_VAR
VAR
  Count: INT;
END_VAR

METHOD Run
IF Start THEN
  Count := Count + 1
  Status := TRUE;
END_IF
END_METHOD
END_FUNCTION_BLOCK
medium
A. Function block name cannot contain underscore
B. Missing semicolon after Count := Count + 1
C. Output variable Status should be input
D. Incorrect keyword METHOD used

Solution

  1. Step 1: Check syntax inside the method

    The line Count := Count + 1 is missing a semicolon at the end, which is required in structured text.
  2. Step 2: Verify other parts

    METHOD keyword is valid, output variable can be named Status, and underscores are allowed in names.
  3. Final Answer:

    Missing semicolon after Count := Count + 1 -> Option B
  4. Quick Check:

    Semicolon missing after assignment line [OK]
Hint: Check each line ends with semicolon in structured text [OK]
Common Mistakes:
  • Ignoring missing semicolons
  • Thinking METHOD keyword is invalid
  • Assuming variable naming rules are stricter
5. You want to create a function block TimerFB that counts seconds when Enable input is TRUE and resets when Reset input is TRUE. Which internal variable type should you use to store the count so it keeps its value between calls?
hard
A. VAR_INPUT
B. VAR_OUTPUT
C. VAR (internal variable)
D. VAR_TEMP

Solution

  1. Step 1: Understand variable types in function blocks

    VAR_INPUT and VAR_OUTPUT are for inputs and outputs, not for storing internal state. VAR_TEMP is temporary and does not keep value between calls.
  2. Step 2: Identify variable type that retains value

    VAR variables inside function blocks keep their value between calls, acting like memory.
  3. Final Answer:

    VAR (internal variable) -> Option C
  4. Quick Check:

    Use VAR for internal memory in function blocks [OK]
Hint: Use VAR for internal memory that persists between calls [OK]
Common Mistakes:
  • Using VAR_TEMP which resets each call
  • Confusing inputs/outputs with internal storage
  • Assuming VAR_INPUT can store internal state
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard