In Beckhoff TwinCAT, there is no single pre-defined global "First Scan" variable like the
bit in Allen-Bradley systems. Instead, you must either access task-specific system information or create a custom flag. Method 1: Using Built-in System Info (Recommended) TwinCAT provides task-specific diagnostics through the array. This contains a FirstCycle boolean that is automatically set to for exactly one scan when the PLC starts or restarts. Structured Text Example:
PROGRAM MAIN VAR fbGetCurTaskIndex : GETCURTASKINDEX; // Function block to find current task index END_VAR
fbGetCurTaskIndex(); // Call the FB to refresh the index
IF _TaskInfo[fbGetCurTaskIndex.index].FirstCycle THEN // Place initialization logic here // Example: Resetting counters or setting default setpoints END_IF Use code with caution. Copied to clipboard : This method utilizes the PlcTaskSystemInfo data structure available in the TwinCAT system.
: Highly accurate; resets every time the PLC transitions from STOP to RUN or after a power cycle. Method 2: Manual Flag (The "Standard" Way)
A common practice among developers is to manually declare a global variable that initializes as and is immediately set to after use. Structured Text Example:
PROGRAM MAIN VAR bFirstScan : BOOL := TRUE; // Initializes to TRUE on startup END_VAR
IF bFirstScan THEN // Perform one-time tasks bFirstScan := FALSE; // Permanent off for the remainder of runtime END_IF Use code with caution. Copied to clipboard
: Simplest to implement and easy to read for engineers coming from other platforms.
: May not behave identically to system flags during certain "Online Change" scenarios depending on how variables are re-initialized. AllTwinCAT Comparison of Methods _TaskInfo.FirstCycle Manual Flag ( BOOL := TRUE Setup Complexity Moderate (Requires FB call) Reliability High (System-managed) Medium (Dependent on initialization) Task Awareness Specific to the calling task Global or Local depending on declaration Standard Usage Professional/Library level General Application level Use Cases for First Scan Bits Initialization
: Setting initial values for PID loops or communication buffers. Resetting Sequences : Ensuring SFC (Sequential Function Chart) sequences start at the initial step. Communication Setup
: Triggering initial requests for external fieldbus devices like EtherNet/IP Beckhoff Information System Function Block Diagram
Understanding the Beckhoff First Scan Bit: A Comprehensive Guide
In the world of industrial automation, programmable logic controllers (PLCs) play a crucial role in controlling and monitoring various processes. Beckhoff, a renowned German-based company, has been at the forefront of PLC technology, providing innovative solutions for a wide range of industries. One of the key features of Beckhoff PLCs is the "First Scan Bit," a concept that has significant implications for PLC programming and operation. In this article, we will delve into the world of Beckhoff PLCs and explore the concept of the First Scan Bit in detail.
What is a Beckhoff PLC?
Before we dive into the First Scan Bit, let's take a brief look at Beckhoff PLCs. Beckhoff Automation GmbH & Co. KG is a leading global supplier of automation technology, including PLCs, human-machine interfaces (HMIs), and motion control systems. Their PLCs, also known as TwinCAT (Twin Computer) systems, are widely used in various industries, such as automotive, aerospace, food and beverage, and more.
Beckhoff PLCs are known for their flexibility, scalability, and high performance. They offer a range of PLC platforms, from compact, entry-level devices to high-end, rack-based systems. One of the key features of Beckhoff PLCs is their ability to execute PLC code in a Windows-based environment, allowing for seamless integration with other Windows applications.
What is the First Scan Bit?
The First Scan Bit, also known as the "First Cycle Bit" or "Initialization Bit," is a special bit in Beckhoff PLCs that indicates when the PLC is executing its first scan cycle. In other words, it signals that the PLC is starting up and executing its program for the first time.
The First Scan Bit is a digital output that is automatically set by the PLC during its startup sequence. When the PLC is powered on or reset, it executes a series of internal checks and initializations before starting to execute the user program. During this first scan cycle, the First Scan Bit is set to TRUE (or 1).
Why is the First Scan Bit important?
The First Scan Bit is essential for several reasons:
How to use the First Scan Bit in Beckhoff PLCs
To use the First Scan Bit in a Beckhoff PLC, you need to access the PLC's system variables. The First Scan Bit is typically represented by a specific system variable, such as FirstScan or InitDone.
Here are the general steps to use the First Scan Bit:
FirstScan).Example: Using the First Scan Bit in TwinCAT 3
In TwinCAT 3, the First Scan Bit is represented by the system variable FirstScan. Here's an example of how to use it in a simple PLC program:
PROGRAM Example
VAR
FirstScan : BOOL;
END_VAR
BEGIN
IF FirstScan THEN
// Execute initialization code here
// e.g., set default values, initialize variables
FirstScan := FALSE;
END_IF
// Rest of the user program...
END_PROGRAM
In this example, the FirstScan system variable is used to execute an initialization code segment during the first scan cycle. Once the initialization is complete, the FirstScan bit is reset to FALSE.
Conclusion
The Beckhoff First Scan Bit is a powerful feature that allows PLC programmers to execute specific code segments during the first scan cycle of a PLC. By understanding the concept of the First Scan Bit, developers can create more efficient, safe, and reliable PLC programs. Whether you're a seasoned PLC programmer or just starting out, the First Scan Bit is an essential concept to grasp when working with Beckhoff PLCs.
In this article, we've provided a comprehensive overview of the Beckhoff First Scan Bit, including its definition, importance, and usage. By following the guidelines outlined here, you'll be able to harness the power of the First Scan Bit in your own PLC projects.
In Beckhoff TwinCAT, there is no single global system bit like the Allen-Bradley S:FS. Instead, you use task-specific system information or a manual initialization variable. 1. Built-in FirstCycle Bit
The most robust way is to use the PlcTaskSystemInfo structure, which contains a FirstCycle boolean. This bit is TRUE only during the very first execution of that specific task after the TwinCAT runtime starts. Implementation Example (Structured Text):
VAR fbGetCurTaskIdx : GETCURTASKINDEX; // Function block to find the current task ID bFirstScan : BOOL; END_VAR fbGetCurTaskIdx(); // Call the FB // Access the system's internal task info array bFirstScan := _TaskInfo[fbGetCurTaskIdx.index].FirstCycle; IF bFirstScan THEN // Insert initialization logic here END_IF Use code with caution. Copied to clipboard
Behavior: This bit usually only triggers when the TwinCAT Runtime is started or restarted. Simply stopping and starting the PLC code with the "Start/Stop" commands in the IDE may not reset this bit. 2. Custom Initialization Variable
If you need a bit that resets every time you "Stop" and "Start" the PLC program (warm restart), the standard practice is to create a non-persistent variable that defaults to TRUE and is set to FALSE at the end of the scan. Implementation Example:
Declare a global or local variable: bInitialized : BOOL := FALSE; Logic:
IF NOT bInitialized THEN // Initialization code here bInitialized := TRUE; END_IF Use code with caution. Copied to clipboard
Behavior: Because TwinCAT resets non-persistent variables to their initial state upon a program start, bInitialized will be FALSE on the first scan, allowing your logic to run once. 3. Legacy Hardware (CX1010)
On older hardware like the CX1010, some technical references mention a specific status bit (Bit 4) in certain control parameters that is set for the first scan after power-up. Key Comparison PlcTaskSystemInfo.FirstCycle Custom bInitialized Variable Best for System-level startup/initialization Logic-level resets/warm restarts Reset Trigger TwinCAT Runtime Restart PLC Program Start (Start/Stop) Setup Requires GETCURTASKINDEX Simple declaration
Beckhoff's TwinCAT 3 environment does not have a dedicated pre-defined "first scan" system bit like Allen-Bradley's S:FS. Instead, developers typically implement this functionality manually using an initial value or by referencing specific PLC task variables. Method 1: Manual Boolean (Most Common)
The most straightforward way is to declare a global variable that resets itself after the first cycle.
Declare Variable: In your Global Variable List (GVL) or program, declare a BOOL with an initial value of TRUE. VAR_GLOBAL bFirstScan : BOOL := TRUE; END_VAR Use code with caution. Copied to clipboard
Reset Logic: At the very end of your MAIN program (or the last program executed in your task), set this bit to FALSE.
// Your logic here... IF bFirstScan THEN // Initialization code END_IF // Last line of the program bFirstScan := FALSE; Use code with caution. Copied to clipboard Method 2: Using PLC Task System Variables
For a more "built-in" feel, you can access internal PLC task information. Beckhoff provides a structure that tracks the scan count of a task. Variable: _TaskInfo[Index].CycleCount
Logic: If the CycleCount is 1, it is the first scan. This is useful if you need to know the first scan of a specific task rather than the entire PLC. Method 3: Initialization in POUs (FB_init)
If you are using Function Blocks, TwinCAT 3 supports the FB_init method. This is a specialized sub-method that runs once when the block is instantiated (during PLC startup or after a download), making it the cleanest way to handle block-specific initializations. Why use a First Scan Bit? beckhoff first scan bit
Resetting Latches: Clearing OTL (Latches) or variables that must start in a known state.
Loading Recipes: Triggering a one-time read from a CSV file or database.
Communication Init: Establishing initial handshake bits with HMIs or other PLCs.
In Beckhoff TwinCAT, the First Scan Bit is a system flag used to execute logic exactly once when the PLC transitions from Config/Stop to Run mode. It is essential for initializing variables, resetting timers, or triggering one-time communication handshakes. How to Access the First Scan Bit
TwinCAT provides a built-in system variable for this purpose within the PlcAppSystemInfo structure. You do not need to create a global variable manually; you can access it via the TwinCAT_SystemInfoVarList. Variable Name: _AppInfo.bFirstCycle Data Type: BOOL
Behavior: This bit is TRUE during the very first execution cycle of the PLC task and automatically switches to FALSE for all subsequent cycles. Implementation Example (ST)
You can use this bit in Structured Text to set default values at startup:
IF _AppInfo.bFirstCycle THEN // Initializing setpoints fTargetTemperature := 22.5; bSystemReady := FALSE; // Resetting operational counters nCycleCounter := 0; END_IF Use code with caution. Copied to clipboard Key Use Cases
Variable Initialization: Setting non-persistent variables to a known starting state.
Pulse Triggers: Triggering a TP (Timer Pulse) or R_TRIG that needs to fire immediately upon startup.
Communication Reset: Sending a "Reset" or "Init" command to external devices (like drives or Vision systems) over EtherCAT.
Loading Recipes: Reading a default parameter set from a file or database during the first task execution. Important Considerations
Multiple Tasks: If your project has multiple PLC tasks, _AppInfo.bFirstCycle is local to the context of the task it is called in.
Persistent Variables: Do not use the first scan bit to overwrite PERSISTENT or RETAIN variables unless you intentionally want to ignore their saved values upon every reboot.
Manual Implementation: If you prefer not to use the system global, you can create a local "Init" flag:
IF NOT bInitDone THEN // Do startup logic here bInitDone := TRUE; END_IF Use code with caution. Copied to clipboard
The Sentinel of Startup: Understanding the Beckhoff First Scan Bit
In the realm of industrial automation, the difference between a smoothly running machine and a catastrophic collision often comes down to timing. While the cyclical nature of Programmable Logic Controllers (PLC) implies a repetitive, predictable existence, the transition from a powered-down state to an operational one is a critical window of uncertainty. It is in this precise moment that the "First Scan" bit proves its worth. Within the Beckhoff automation ecosystem—specifically utilizing TwinCAT software—the First Scan bit acts as the essential sentinel of initialization, ensuring that logic executes correctly before the physical world is engaged.
To understand the importance of the First Scan bit, one must first appreciate the architecture of a PLC. A PLC operates on a scan cycle: reading inputs, executing logic, and writing outputs. Under normal operation, this cycle repeats endlessly. However, the very first cycle after a power-up or a program reset presents a unique problem. At this specific moment, input data may not have settled, variables may be holding default values rather than retained ones, and physical actuators might be in unknown positions. If the control logic were to execute standard commands immediately, it could lead to unintended consequences, such as commanding a cylinder to extend before verifying it is retracted, or resetting a recipe to default values instead of loading the last saved state.
In the Beckhoff TwinCAT environment, this functionality is primarily handled through system-defined variables, specifically within the System task info structures. While various versions of TwinCAT exist, the concept remains consistent: the system generates a Boolean flag that is TRUE for exactly one cycle—the very first cycle after the controller enters the "Run" state. In TwinCAT 3, this is often accessed via the PlcTaskSystemInfo structure or the _TaskInfo interface, providing developers with a programmable trigger that occurs once and only once per startup.
The primary utility of the First Scan bit lies in initialization. It serves as the logical "clean slate" mechanism. For instance, in complex motion control applications involving Beckhoff’s NC (Numerical Control) or robotics, the First Scan routine is used to verify the actual position of axes against their commanded positions. It allows the programmer to suppress motion commands until the system has verified that communication with servo drives is healthy. Furthermore, it is instrumental in state machine logic. By forcing the state machine into a specific "Init" or "Home" state on the first scan, the engineer ensures the machine follows a strict, safe sequence of startup events, regardless of the state the machine was in when it was last powered off.
Beyond simple initialization, the First Scan bit is crucial for the handling of Retain variables. TwinCAT offers robust mechanisms for persistent data, but logic is often required to handle the scenario where no retained data exists (a first boot) versus when it does. The First Scan bit allows the code to differentiate between these scenarios, loading defaults only when necessary or validating the integrity of retained data before use.
It is important to distinguish the First Scan bit from the "Cold Start" or "Warm Start" methods. While the First Scan bit fires in both scenarios, the logic attached to it can be bifurcated. A skilled programmer may use additional system flags to determine if the startup is a warm restart (retaining memory) or a cold restart (memory cleared), allowing the First Scan logic to behave differently depending on the severity of the reset. This granularity offers a level of control that separates robust industrial code from hobbyist experimentation.
In conclusion, the Beckhoff First Scan bit is far more than a simple Boolean flag; it is a foundational element of reliable software engineering in automation. It bridges the gap between the static, powered-down world and the dynamic, moving machine. By providing a deterministic method to execute initialization logic exactly once, it safeguards machinery, protects processes, and ensures that every production cycle begins with a known, safe, and calculated start. In the symphony of industrial control, the First Scan bit is the conductor’s initial tap of the baton—the signal that establishes order before the performance truly begins.
In Beckhoff's TwinCAT environment, there isn't a single "fixed" system bit like the
found in Allen-Bradley controllers. Instead, developers typically use one of two methods to detect the first scan cycle of a PLC task: a built-in system variable or a manual "home-made" boolean flag. 1. Built-in Method: PlcTaskSystemInfo TwinCAT provides a structured data type called PlcTaskSystemInfo that contains a specific boolean member for this purpose: FirstCycle
To use it, you must retrieve the current task index and access the system info array: Function Block GETCURTASKINDEX to find which task is currently running. System Variable : Access the global array using that index. Example Implementation (Structured Text):
VAR fbGetCurTaskIndex : GETCURTASKINDEX; END_VAR
fbGetCurTaskIndex(); // Call the function block
IF _TaskInfo[fbGetCurTaskIndex.index].FirstCycle THEN // Logic here only executes on the very first scan END_IF Use code with caution. Copied to clipboard 2. Manual Method: Initialized Boolean
A common practice in IEC 61131-3 programming is to create a local or global boolean variable that defaults to and is turned at the end of the first cycle. Initialization : Declare a variable like bFirstScan with an initial value of : At the very end of your main program, set it to
: This method is portable across different PLC brands and doesn't require specific TwinCAT system function calls. Example Implementation:
VAR bFirstScan : BOOL := TRUE; // Initialized to TRUE END_VAR
IF bFirstScan THEN // Perform initialization (e.g., setting default values) END_IF
// Last line of the program bFirstScan := FALSE; Use code with caution. Copied to clipboard Why use a First Scan Bit? Initialization
: Setting initial values for variables that aren't retentive. Communication Setup
: Triggering handshake or connection logic that only needs to happen once upon startup. Safety Resets
: Ensuring certain outputs or states are cleared before the main logic begins. hardware initialization How to Configure the FirstScan Bit in Siemens TIA Portal
Here’s a technical feature article exploring the First Scan Bit in Beckhoff TwinCAT systems.
The "Beckhoff first scan bit" is not a single feature but a concept implemented through various patterns. For simple projects, a F_TRIG on a TRUE variable is sufficient. For robust, reusable code, use FB_Init in function blocks. For system-wide initialization that must run before cyclic logic, use the INIT section.
Final recommendation for most engineers:
F_TRIG method at the top of your MAIN program.FB_Init in every function block.INIT with a check of the EtherCAT state machine.Remember: A well-implemented first scan routine separates unreliable prototypes from industrial-grade automation. Take the time to initialize deliberately—your machine's safe operation depends on it.
Further Reading:
Tc3_Standard Library DocumentationFB_EcCoEADsReadHave a specific first scan challenge? Visit the Beckhoff Community forums or consult your local Beckhoff support engineer.
To detect the first scan in Beckhoff TwinCAT, you can read the system task info or create a classic initialization variable.
TwinCAT does not have a global hardware bit like Allen-Bradley's S:FS. Instead, it handles this through software or task-level data types. 🚀 Method 1: The Built-in System Variable (Best Practice)
TwinCAT provides an array called _TaskInfo that holds real-time diagnostic data for every task running on the processor. You must fetch the specific task index first to avoid hardcoding errors. Structured Text Implementation:
VAR fbGetCurTaskIdx : GETCURTASKINDEX; // Fetches the current task's index bFirstScan : BOOL; // Your usable First Scan bit END_VAR // 1. Get the current task index fbGetCurTaskIdx(); // 2. Read the FirstCycle boolean from the task system info bFirstScan := _TaskInfo[fbGetCurTaskIdx.index].FirstCycle; Use code with caution. Copied to clipboard In Beckhoff TwinCAT, there is no single pre-defined
Pros: Highly accurate and managed entirely by the TwinCAT runtime.
Cons: Requires a couple of lines of code rather than referencing a direct tag. 🛠️ Method 2: The Variable Initialization Method
If you are used to pure IEC 61131-3 logic or want something simple that does not require checking task arrays, you can use variable initialization. Structured Text Implementation:
VAR bFirstScan : BOOL := TRUE; // Starts as TRUE on boot END_VAR // Place your first-scan initialization logic here IF bFirstScan THEN // Execute your one-time startup code // Turn it off at the end of the first scan bFirstScan := FALSE; END_IF Use code with caution. Copied to clipboard Pros: Extremely fast and simple.
Cons: If you reset the PLC program without a hard power cycle or runtime restart, the behavior depends on whether you have retained the variable. ⚠️ Important Considerations
⚠️ Run Mode Transitions: Note that in TwinCAT 3, _TaskInfo[].FirstCycle behaves strictly as the first cycle after the TwinCAT Runtime starts up (moving to Green mode). Toggling the PLC project between STOP and RUN alone does not always re-trigger it unless the system is restarted.
⚠️ Multi-Task Execution: If you use Method 1 in multiple tasks (e.g., a fast cyclic task and a slower periodic task), it will evaluate properly for each task's respective first execution loop.
Which of these two methods are you planning to use for your specific project? Beckhoff CX1010 first scan | PLCtalk - Interactive Q & A
In Beckhoff TwinCAT (2 and 3), there is no single "magic" global bit like the S:FS in Allen-Bradley . Instead, you can access the "First Scan" status through built-in system variables or by creating a custom initialization flag. 1. Using Built-in System Info (FirstCycle)
The most reliable way to detect the first scan in TwinCAT 3 is to use the PlcTaskSystemInfo structure . Every task has an associated system structure that includes a FirstCycle boolean . Example Implementation (Structured Text):
VAR fbGetCurTaskIdx : GETCURTASKINDEX; // Function block to get current task index bFirstScan : BOOL; END_VAR fbGetCurTaskIdx(); // Call the FB to refresh current task info bFirstScan := _TaskInfo[fbGetCurTaskIdx.index].FirstCycle; IF bFirstScan THEN // Logic here only runs on the very first PLC scan // e.g., Initializing setpoints or resetting state machines END_IF Use code with caution. Copied to clipboard 2. Manual Global Variable Flag
A common "best practice" for portability across different PLC brands is to create your own flag in a Global Variable List (GVL) . Declare it with an initial value:
VAR_GLOBAL bIsFirstScan : BOOL := TRUE; // Starts TRUE when the PLC runtime begins END_VAR Use code with caution. Copied to clipboard
Reset it at the end of your main program:Place this line at the very bottom of your MAIN program or the last task to execute :
// Main logic uses bIsFirstScan... // Final line of code: bIsFirstScan := FALSE; Use code with caution. Copied to clipboard 3. SFC Initialization Flag
If you are using Sequential Function Chart (SFC) programming, TwinCAT provides implicit variables called SFC Flags .
SFCInit: When set to TRUE, the sequence is reset to the initial step .
SFCReset: Resets the sequence and continues processing from the initial step . Key Usage Considerations
Cold vs. Warm Restart: The FirstCycle bit typically triggers when the Runtime starts . Simple PLC "Stop" and "Start" commands in the IDE might not always reset this bit unless the entire TwinCAT system is restarted or a new configuration is activated .
Multiple Tasks: If your project has multiple tasks (e.g., a fast 1ms task and a slow 100ms task), each task has its own FirstCycle flag. Ensure you are checking the flag for the specific task where your initialization logic resides . RSLogix 5000 First Scan Bit (S:FS) Programming Guide
In Beckhoff TwinCAT systems, there is no single global "S:FS" bit like those found in Rockwell (Allen-Bradley) controllers . Instead, users typically leverage the PlcTaskSystemInfo
structure or create a custom initialization variable to manage first-scan logic. Beckhoff Information System Key Ways to Implement a First Scan Bit
There are two primary methods used in TwinCAT to achieve "first scan" functionality: System Variable Method : The most robust way is using the FirstCycle member of the PlcTaskSystemInfo structure. How it works : Every PLC task has a system variable which contains a boolean FirstCycle . This bit is only during the very first cycle of that specific task.
: It is built into the runtime and is highly reliable for initializing state machines or variables. Implementation Example
IF _TaskInfo[GETCURTASKINDEX()].FirstCycle THEN // Your initialization logic here END_IF; Use code with caution. Copied to clipboard Custom Variable Method
: You can manually create a non-retentive boolean variable initialized as How it works : Define a with an initial value of
. At the very end of your main program, set this variable to
. It will then act as a first-scan bit for every subsequent cycle. : Simple to understand and portable across different IEC 61131-3 platforms. Beckhoff Information System User Experience and "Reviews" Behavioral Quirks : Some users have noted that the FirstCycle
bit may only trigger when the TwinCAT runtime is fully restarted, rather than just stopping and starting the PLC code execution via the developer interface. Initialization Importance
: In industrial settings, a first-scan bit is considered essential for resetting retentive memory and ensuring equipment starts in a safe, predictable state. Alternative for Advanced Users
: For complex setups, some developers prefer using a dedicated Initialization (INIT) block
or state machine that runs once before the main cyclic logic begins. DigiKey TechForum
For official documentation on these system variables, you can refer to the Beckhoff Information System Are you looking to initialize specific variables or are you migrating logic from another PLC platform RSLogix 5000 First Scan Bit (S:FS) Programming Guide
In the world of Beckhoff TwinCAT and industrial automation, the "First Scan Bit" is a fundamental tool for ensuring your PLC starts in a predictable, safe state. If you’ve ever worked with Siemens (where it’s a system bit like FirstScan) or Allen-Bradley (using the S:FS bit), you know how vital this is.
In Beckhoff’s TwinCAT 3 environment, there isn’t a single hard-coded bit in the global memory by default, but the system provides a specialized mechanism to create one that is far more powerful than a simple boolean. What is the First Scan Bit?
The First Scan Bit is a flag that is TRUE for exactly one PLC cycle when the controller moves from "Config" or "Stop" mode into "Run" mode. After that first execution of the logic, the bit turns FALSE and remains so until the PLC is restarted or the code is re-downloaded. Why Do You Need It?
Without a initialization bit, your PLC logic simply resumes from its last state or starts with default values that might not be appropriate for a running machine. Common use cases include:
Initializing Setpoints: Setting default temperatures, speeds, or timers.
Resetting State Machines: Ensuring your sequences (SFC) start at "Step 0."
Clearing Alarms: Wiping the slate clean on startup so old errors don't prevent a start.
Communication Handshakes: Establishing a "heartbeat" or initial connection status with HMIs or third-party devices. How to Implement "First Scan" in TwinCAT 3 There are two primary ways to handle this in Beckhoff. 1. The Manual Method (Most Common)
Most TwinCAT developers create a global boolean variable and set it to TRUE by default. At the very end of their main program, they set it to FALSE. Variable Declaration (GVL): VAR_GLOBAL bFirstScan : BOOL := TRUE; END_VAR Use code with caution. Main Logic (MAIN PRG):
IF bFirstScan THEN // Perform Initialization Tasks here iTargetVelocity := 1500; bMachineReady := FALSE; END_IF // All other machine logic goes here... // The very last line of the program: bFirstScan := FALSE; Use code with caution. 2. Using FB_GetCurTaskIndex (The Pro Method)
TwinCAT provides internal system information via the Tc2_System library. You can check if the current cycle is the very first one by looking at the system task info.
VAR fbGetTaskIndex : FB_GetCurTaskIndex; nCycleCount : UDINT; END_VAR fbGetTaskIndex(); nCycleCount := _TaskInfo[fbGetTaskIndex.index].CycleCount; IF nCycleCount = 1 THEN // This is the first scan END_IF Use code with caution.
Note: This method is more robust because it relies on the system's own cycle counter rather than a variable you might accidentally overwrite elsewhere. Best Practices
Placement Matters: If you use the manual variable method, ensure the line bFirstScan := FALSE; is at the very bottom of your MAIN task. If you put it in a sub-function, other parts of your program might miss the "True" state.
Avoid "Retain" Variables: Never make your First Scan bit a RETAIN or PERSISTENT variable. It needs to reset every time the PLC power cycles.
Safety First: Use the first scan to ensure all physical outputs are in a "Safe/Off" state before the logic takes over.
The Beckhoff First Scan bit is your "clean slate" button. Whether you use a simple boolean flag or the system's cycle counter, implementing this ensures that your machine starts up with the correct parameters every time, preventing "ghost" data from causing erratic behavior during commissioning. : Highly accurate; resets every time the PLC
In the world of industrial automation, specifically within the Beckhoff TwinCAT environment, the "first scan bit" is a fundamental concept used to initialize logic, reset variables, or trigger one-time events when a PLC program transitions from Stop to Run mode.
Understanding how to implement and utilize this bit effectively ensures that your machines start up in a safe, predictable state every time the controller is powered on or the code is restarted. What is a First Scan Bit?
A first scan bit is a boolean flag that remains TRUE for exactly one execution cycle of the PLC task. After the first logic solve is complete, the bit drops to FALSE and stays there until the PLC is restarted.
Unlike some traditional PLCs (like Allen-Bradley’s S:FS bit) that have a predefined system variable, Beckhoff’s TwinCAT allows for several ways to achieve this functionality depending on your version and preference. Methods to Implement First Scan in TwinCAT 1. Using the TwinCAT System Info (The Pro Way)
The most robust method involves using the built-in PlcTaskSystemInfo structure. This provides real-time data about the current task. Variable: _TaskInfo[index].FirstCycle
How it works: This system variable is automatically managed by the TwinCAT runtime.
Benefit: No manual coding is required to reset the bit; it is inherently tied to the task execution. 2. Manual Logic (The Classic Way)
If you prefer a portable method that works across almost any IEC 61131-3 platform, you can create your own logic using a global variable.
Step 1: Declare a global boolean, e.g., bFirstScan : BOOL := TRUE;.
Step 2: At the very end of your MAIN routine, add: bFirstScan := FALSE;.
How it works: On startup, the variable initializes to TRUE. The logic runs once, and then the assignment at the bottom kills the bit for all subsequent cycles. 3. Using the 'Init' Attribute
TwinCAT 3 supports the attribute 'init_on_on_online_change' or specific FB_init methods. While more advanced, these are used to run initialization code specifically when a function block is instantiated or the PLC starts. Common Use Cases
🚀 Initialization of SetpointsEnsures that PID gains, speed limits, or timers start with default "safe" values rather than zeros.
🔄 Resetting State MachinesForces your Sequential Function Chart (SFC) or CASE statements to jump to the 'IDLE' or 'INIT' state regardless of where they were during the last shutdown.
📡 Communication HandshakesTriggers a "Hello" or synchronization pulse to external devices, such as HMIs or SQL databases, to signal that the PLC is back online. Best Practices and Pitfalls
Execution Order Matters: If you use a manual first scan bit, ensure it is set to FALSE at the very end of your program. If you do it at the top, the rest of your logic won't see the TRUE state.
Distributed Tasks: If your TwinCAT project has multiple tasks (e.g., a fast 1ms task and a slow 10ms task), remember that each task has its own "first cycle."
Avoid Logic Overload: Don't cram too much heavy processing into the first scan. If you have massive data to load, consider a dedicated "Initialization" state that spans multiple cycles.
⚠️ Key Reminder: Always use the first scan bit to put your machine into a Safe State. Never assume the hardware is in the same position it was when the power went out.
In Beckhoff TwinCAT, the "first scan bit" is a fundamental tool used to execute initialization code only once when the PLC starts or transitions into Run mode. Unlike some other platforms that use a fixed system bit (like Siemens' S:FS), TwinCAT provides a more flexible approach using built-in system structures or manual variable initialization. Direct Solution for First Scan Bit
The most reliable way to access a "first scan" state in TwinCAT 3 is through the global array _TaskInfo. This structure contains real-time information for each task running on the controller. Standard Implementation (Structured Text):
VAR fbGetCurTaskIndex : GETCURTASKINDEX; bFirstScan : BOOL; END_VAR fbGetCurTaskIndex(); // Get the index of the current PLC task bFirstScan := _TaskInfo[fbGetCurTaskIndex.index].FirstCycle; // Extract the bit IF bFirstScan THEN // Place initialization logic here (e.g., loading presets or clearing memory) END_IF Use code with caution. Copied to clipboard 1. Understanding System Information Structure
The FirstCycle bit is a member of the PlcTaskSystemInfo data type. This structure is part of the TwinCAT 3 PLC library and provides diagnostic data directly from the real-time kernel. Accessing it requires the GETCURTASKINDEX function block to identify which task is currently executing, as TwinCAT can run multiple tasks with different cycle times. 2. Alternative "Manual" Method
Many developers prefer a manual method for simplicity or for use in older versions of TwinCAT where system structures might differ. This relies on the initialization value of a boolean variable.
Step 1: Declare a global or local boolean variable initialized to TRUE.
Step 2: Use this variable as a condition for your initialization code.
Step 3: At the end of your program or inside the conditional block, set the variable to FALSE. Manual Code Example:
VAR bInitialScan : BOOL := TRUE; // Initialized to TRUE on startup END_VAR IF bInitialScan THEN // Startup logic bInitialScan := FALSE; // Permanent reset after first run END_IF Use code with caution. Copied to clipboard 3. Applications and Best Practices The first scan bit is essential for:
Initializing Variables: Setting default values for non-persistent variables.
Triggering Communication: Starting handshake sequences with external devices or HMIs.
Safety Checks: Ensuring all actuators and states are in a safe "Home" position before the main logic begins. Summary of First Scan Options Method Implementation System Info _TaskInfo[index].FirstCycle Native, accurate, and task-specific. Manual Bit Conditional BOOL reset to FALSE Simplest logic, works across all platforms. Function Block GETCURTASKINDEXEX() Faster implementation as it doesn't require instantiation.
Final ResultIn Beckhoff TwinCAT, the First Scan Bit is accessed via the _TaskInfo system array using the FirstCycle property. This bit is uniquely TRUE during the first execution cycle of a task, allowing for precise system initialization. First Scan Bit - OpenPLC Forum
You can easily test it by:
Creating a simple counter:
IF fbFirstScan.bFirstScan THEN
nFirstScanCounter := nFirstScanCounter + 1;
END_IF
Run → Login → Download
→ Counter increments by 1
Stop → Start PLC (without download)
→ Counter does not increment (warm start without new program)
→ In many cases, bFirstScan stays FALSE here unless configured to detect warm starts.
FB_Init Method (Object-Oriented)For advanced TwinCAT 3 users working with Function Blocks, the most elegant and robust "first scan" is not a bit at all—it's the object constructor: FB_Init.
When you instantiate a function block, TwinCAT automatically calls its FB_Init method once.
FUNCTION_BLOCK FB_DriveController VAR_INPUT bEnable : BOOL; END_VAR VAR_OUTPUT bReady : BOOL; END_VAR VAR fSpeed : REAL; END_VAR
// This runs once when the FB is created (first scan of the FB) METHOD FB_Init : BOOL VAR_INPUT bInitRetains : BOOL; // TRUE if retain variables are restored bInCopyCode : BOOL; // TRUE if FB is copied END_VAR fSpeed := 0.0; // Initialize internal variable bReady := FALSE; END_METHOD
Advantages:
bInitRetains parameter tells you if previous retain values were loaded.When to use this: In large OOP-based TwinCAT projects with many reusable function blocks.
The "First Scan" bit in Beckhoff TwinCAT PLC systems is a boolean status flag indicating the PLC program's initial execution cycle after startup, download, or reset. It enables safe, deterministic initialization of variables, hardware states, and communication interfaces before normal cyclic operation proceeds.
The Beckhoff First Scan bit is a small, easily overlooked tool that separates professional, robust PLC code from fragile, “works-most-of-the-time” logic. By taking explicit control of the first cycle, you eliminate startup surprises, protect hardware, and ensure your TwinCAT application starts every time in a predictable, safe state.
Next time you write a new PLC program, ask yourself: “If this were a cold start right now, would my system behave safely?” If the answer isn’t an immediate “yes,” you need FirstScan.
Have a tricky Beckhoff initialization issue? Share your experience in the comments or contact your local Beckhoff automation partner.
| Do | Don't |
|----|-------|
| Use FB_FirstScan from Tc2_System | Rely on manual := TRUE flags |
| Keep first scan logic short | Put heavy processing inside first scan |
| Set outputs to safe defaults | Assume all retentive data is valid |
| Combine with Tc2_Standard for consistent behavior | Use first scan for normal logic flow |
Simple flag:
VAR_GLOBAL
FirstScan : BOOL := TRUE;
END_VAR
IF FirstScan THEN
// initialize variables, outputs, communication
Output1 := FALSE;
ResetAlarms();
FirstScan := FALSE;
END_IF
Edge detection using task cycle counter:
VAR
CycleCount : UDINT := 0;
END_VAR
CycleCount := CycleCount + 1;
IF CycleCount = 1 THEN
// first scan logic
END_IF
Initialization block with handshake:
FB_Init : InitFB;
// InitFB runs once, sets InitDone BOOL when finished
IF InitDone THEN
// normal operation
ELSE
// hold outputs safe
END_IF