Skip to content

LUA脚本开发 ​

WIFI 版、4G 版与三网版 PLC 都支持 Lua 脚本开发,与梯形图程序并行运行,实现 PLC 逻辑控制与物联网功能的深度融合。

LUA与PLC交互 ​

软元件统一用 plc.名称(地址) 读、plc.名称(地址, 值) 写。地址按十进制解析,不做八进制换算。

lua
-- 读取PLC位元件(返回 0 或 1)
local x0 = plc.x(0)

-- 写入PLC位元件(值可传 0/1 或 true/false)
plc.y(0, 1)

-- 读取PLC字元件(D0,16 位有符号)
local d0 = plc.d(0)

-- 写入PLC字元件
plc.d(0, 1234)

网络通信 ​

所有模块由固件内置并自动加载,不需要 require。

lua
-- Modbus TCP 主站:轮询模式,自动把从站数据搬进 D 区
mbdev = modbus.creat("192.168.1.100", 502)
mbdev:add_channel(1, 400001, modbus.U16, 100, modbus.READ)  -- 从站1的40001 → D100
mbdev:set_time_lunxun(500)                                  -- 轮询间隔 500ms
mbdev:start()

-- MQTT:客户端对象必须用全局变量长期持有,否则会被 GC 回收导致断连
mqttc = mqtt.creat("broker.hivemq.com", 1883, "LP3202-001", "", "")
mqtt.start(mqttc)

timer.start(5000, function()
  -- is_linked 返回整数,必须 == 1
  if mqtt.is_linked(mqttc) == 1 then
    mqtt.publish(mqttc, "topic/test", tostring(plc.d(0)), 1, 0)
  end
end)

mqtt 的调用方式

除构造函数 mqtt.creat 外,每个函数都同时注册在库表和对象元表里,mqtt.publish(客户端, ...) 与 客户端:publish(...) 等价,按习惯选一种即可。

LUA编程完整指南

LUA脚本开发的详细说明(语法、库函数、通信协议、PLC交互等),请参考 LUA编程 模块。


LPPLC 工业物联网云平台 · 软硬件与云平台全栈自研