跳到主要内容

SCL 变量

变量保存 PLC 输入、输出、状态和计算结果;编写任意控制逻辑前都需要先声明。本页说明当前 C# 风格声明、初值和状态使用规则。工程中的输入、输出、DB 和标签应先在项目模型中定义,再按符号名访问。不要写成 Pascal 的 VAR / END_VAR。

位置类别访问生命周期
顶层变量扫描状态读写本代码段每次扫描保留
方法局部变量临时计算读写本次调用
类字段功能块状态读写实例多次扫描之间保留
项目符号工程数据按符号权限项目运行期间

声明变量​

bool startCommand;
int targetSpeed = 100;
string stateText = "Stopped";

语法是“类型 名称”,可用 = 设置初值。带初值时建议一行只声明一个变量。

赋值​

bool enabled = false;
int count = 0;
string message = "Idle";

enabled = true;
count = count + 1;
message = "Running";

左侧必须是可写变量、字段或数组元素。= 不表示相等比较;比较应使用 ==。

命名规则​

  • 名称可包含字母、数字、下划线和中文字符。
  • 首字符不能是数字。
  • 名称区分大小写。
  • 不能使用关键字。
  • 名称应表达信号或工艺含义,不要只写 Data1、Flag2。
bool guardClosed = false;
int completedParts = 0;
string currentStation = "StationA";

顶层变量​

顶层变量适合保存代码段每次扫描都要读取或更新的状态。

bool runState = false;
bool startCommand = false;
bool stopCommand = false;
int startCount = 0;
string lastAction = "None";

if (stopCommand)
{
runState = false;
lastAction = "Stop";
}
else if (startCommand && !runState)
{
runState = true;
startCount = startCount + 1;
lastAction = "Start";
}

需要跨扫描保存的状态应放在稳定的顶层变量或功能块字段中,不要依赖临时局部值。

局部变量​

方法和代码块中的变量只在其词法作用域内可见,适合保存中间结果。

class LimitTools
{
public int Clamp(int value, int low, int high)
{
int result = value;

if (result < low)
{
result = low;
}
else if (result > high)
{
result = high;
}

return result;
}
}

需要跨扫描保存的状态不要放在方法局部变量中。

类字段​

类字段属于功能块实例,同一实例在多次扫描调用之间保留字段状态。

class StartCounter
{
private int count = 0;
public int Count { get; set; }

public void Execute(bool pulse, bool reset)
{
if (reset)
{
count = 0;
}
else if (pulse)
{
count = count + 1;
}

Count = count;
}
}

每个逻辑对象应使用独立实例,避免共享历史状态。

项目符号​

工程中的输入、输出、DB 和标签应先在项目模型中定义,再在 SCL 中按符号名访问。优先使用有含义的符号名,不在教程代码中硬编码物理地址。

编译前检查​

  • 变量在使用前已声明。
  • 变量名大小写一致。
  • 右侧值与左侧类型兼容。
  • 跨扫描状态位于稳定变量或功能块字段中。
  • 临时变量在读取前沿所有分支赋值。