Skip to main content

First Scan Bit: Beckhoff

  • Software-driven flag (common)

  • Edge-detected approach

  • Supervisor/Task-based initialization

  • 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:

    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:

    Have a specific first scan challenge? Visit the Beckhoff Community forums or consult your local Beckhoff support engineer.

    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

    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: beckhoff first scan bit

    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

    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

    The Beckhoff "First Scan Bit" refers to a signal used in TwinCAT PLC programming to execute initialization logic exactly once when the controller starts or enters run mode. Unlike some other PLC platforms that have a fixed system bit like Allen-Bradley's S:FS, Beckhoff TwinCAT provides this functionality through specific system variables or custom logic. Standard Implementation Methods

    There are two primary ways to access or create a "First Scan" signal in Beckhoff TwinCAT:

    System Info Variable (PlcTaskSystemInfo):The most reliable built-in method in TwinCAT 3 is using the FirstCycle boolean found within the PlcTaskSystemInfo structure.

    How to use it: Access the global array _TaskInfo[index] using the GETCURTASKINDEX function block to retrieve the current task's index. Snippet Example:

    IF _TaskInfo[fbGetCurTaskIndex.index].FirstCycle THEN // Your initialization code here END_IF Use code with caution. Copied to clipboard

    Manual Bit Creation:A common "homemade" solution involves declaring a boolean variable with a default value of TRUE.

    Logic: Place code at the very end of your main program that sets this bit to FALSE. Because the variable is initialized to TRUE, it remains so for the entire first scan before being permanently toggled off. Comparison and Review PlcTaskSystemInfo.FirstCycle Manual Custom Bit Reliability Native to TwinCAT; handles task-specific restarts. Highly reliable if implemented at the program's end. Complexity Requires calling GETCURTASKINDEX. Extremely simple to declare and use. Best Use Case

    Large projects with multiple tasks or complex initialization. Quick, single-task projects or basic logic. Summary of Benefits

    Initialization: Essential for setting default values for retentive memory variables.

    State Reset: Ensures equipment begins in a safe, known state.

    Task Specificity: Allows initialization to be tied to the specific timing of individual tasks rather than just global power-up. RSLogix 5000 First Scan Bit (S:FS) Programming Guide

    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. Software-driven flag (common)

    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 equivalent of a "first scan bit" is the firstCycle variable found within the system task information. This bit is automatically set to TRUE only during the very first execution cycle of a PLC task, making it ideal for one-time initialization logic. How to Access the First Scan Bit

    You can access this feature through the implicit _TaskInfo array, which contains data for every task running in your PLC project. Syntax (Structured Text):

    IF _TaskInfo[GETCURTASKINDEXEX()].firstCycle THEN // Your initialization code here (e.g., setting default parameters) END_IF Use code with caution. Copied to clipboard Key Characteristics

    Automatic Reset: The system automatically resets this bit to FALSE after the first cycle completes.

    Task-Specific: Because it is part of the task info structure, it correctly identifies the first scan for the specific task it is called within.

    Reliability: It is more robust than manual "first scan" flags (like using a boolean that you set to false at the end of the code), as the PLC runtime handles its state directly. Usage Example

    Commonly used to load recipes, initialize communication drivers, or reset state machines to their starting position upon a PLC cold or warm start. If you'd like, I can show you: Edge-detected approach

    How to manually create a first-scan bit if you're using an older version of TwinCAT.

    How to use it to initialize persistent variables from a file.

    The difference between a cold start and a warm start in relation to this bit. Beckhoff CX1010 first scan | PLCtalk - Interactive Q & A

    Here is a professional, production-ready template for a Beckhoff PLC main program:

    PROGRAM MAIN
    VAR
        bInit : BOOL := TRUE;          // Our first scan flag
        bFirstScanDone : BOOL;
        fbFirstScan : F_TRIG;
        fbEcMaster : FB_EcCoEADsRead;   // EtherCAT utility
        nState : INT;
    END_VAR
    

    // -- First scan detection -- fbFirstScan(CLK := bInit); IF fbFirstScan.Q THEN bFirstScanDone := FALSE;

    // 1. Set global output safe state
    GVL.bEmergencyStop := FALSE;
    GVL.nMotorSpeed := 0;
    // 2. Clear alarms
    GVL.stAlarmBuffer := (Count := 0);
    // 3. Request axes to home (if needed)
    fbAxis1.bHomeRequest := TRUE;
    

    END_IF

    // -- Wait for EtherCAT sync -- nState := fbEcMaster.GetState(); IF nState <> 8 THEN RETURN; // Don't run logic until bus is operational END_IF

    // -- Normal logic after first scan done -- IF NOT bFirstScanDone THEN // Final first-scan tasks that require bus ready fbAxis1.ExecuteHome(); bFirstScanDone := TRUE; END_IF

    // -- Main control loop -- RunMachineLogic();

    // -- Reset the first scan trigger for next init -- bInit := FALSE;


    PROGRAM MAIN
    VAR
        bFirstScan    : BOOL := TRUE;   // Initialize as TRUE
        bFirstScanDone: BOOL := FALSE;
    END_VAR
    

    // First scan detection IF bFirstScan AND NOT bFirstScanDone THEN bFirstScanDone := TRUE; // First scan logic here END_IF

    // Reset the flag after first cycle IF bFirstScanDone THEN bFirstScan := FALSE; END_IF

    ⚠️ Caveat: This method can fail if the PLC is stopped/started without power cycle. Always prefer the system library method.

    Beckhoff TwinCAT offers built-in program-local initialization flags that many users overlook: INIT and EXIT sections within a program.

    PROGRAM MAIN
    VAR
        myOutput : BOOL;
    END_VAR
    

    // INIT section runs once when program is loaded/started INIT myOutput := FALSE; // Set safe state // Home axes, clear arrays, etc.

    // Main cyclic code myOutput := TRUE; // Normal logic

    // EXIT section runs when program stops EXIT myOutput := FALSE;

    Key nuance: The INIT section runs before the first cyclic scan. This is actually earlier than a typical "first scan bit." If you need to guarantee initialization occurs before any other logic, INIT is superior.

    But warning: If you call the program multiple times (e.g., as an action or method), the INIT behavior may change. Use it carefully within the main cyclic task.


    Add the TwinCAT_SystemInfoVarList to your project, then:

    IF TwinCAT_SystemInfoVarList._FirstScan THEN
        // One-time actions
    END_IF