0
0
FreertosHow-ToBeginner · 4 min read

How to Use CODESYS for PLC Programming: Step-by-Step Guide

To use CODESYS for PLC programming, start by creating a new project and selecting your PLC device. Then write your control logic using IEC 61131-3 languages like Structured Text or Ladder Diagram, compile, and download the program to your PLC for execution.
📐

Syntax

CODESYS supports IEC 61131-3 programming languages. The most common syntax is Structured Text (ST), which looks like simple programming code. Key parts include variable declarations, assignments, and control structures like IF and FOR.

Example syntax elements:

  • VAR ... END_VAR: Declare variables
  • IF ... THEN ... ELSE ... END_IF: Conditional logic
  • FOR ... TO ... DO ... END_FOR: Loops
  • :=: Assignment operator
iec_st
PROGRAM PLC_Program
VAR
  counter : INT := 0;
  flag : BOOL := FALSE;
END_VAR

IF counter < 10 THEN
  counter := counter + 1;
  flag := TRUE;
ELSE
  flag := FALSE;
END_IF
END_PROGRAM
💻

Example

This example shows a simple counter that increments each cycle until it reaches 10, then stops.

iec_st
PROGRAM CounterExample
VAR
  count : INT := 0;
  done : BOOL := FALSE;
END_VAR

IF NOT done THEN
  count := count + 1;
  IF count >= 10 THEN
    done := TRUE;
  END_IF
END_IF
END_PROGRAM
Output
After 10 cycles, count = 10 and done = TRUE
⚠️

Common Pitfalls

Common mistakes when using CODESYS include:

  • Not selecting the correct PLC device before programming, causing download errors.
  • Forgetting to declare variables before use, which leads to compilation errors.
  • Using incorrect syntax like = instead of := for assignment.
  • Not compiling the project before downloading to the PLC.

Always check your variable declarations and syntax carefully.

iec_st
(* Wrong assignment syntax *)
count = count + 1;  (* This will cause an error *)

(* Correct assignment syntax *)
count := count + 1;
📊

Quick Reference

ConceptSyntax ExampleDescription
Variable DeclarationVAR x : INT; END_VARDefines variables used in the program
Assignmentx := 5;Assigns value 5 to variable x
If StatementIF x > 0 THEN y := 1; END_IFExecutes code if condition is true
For LoopFOR i := 1 TO 10 DO sum := sum + i; END_FORRepeats code block 10 times
Program BlockPROGRAM MyProgram ... END_PROGRAMDefines the main program block

Key Takeaways

Start by creating a new project and selecting your PLC device in CODESYS.
Write your control logic using IEC 61131-3 languages like Structured Text.
Always declare variables before use and use := for assignments.
Compile your program before downloading it to the PLC device.
Test your program step-by-step to avoid common syntax and logic errors.