From 637bbef35749132e887e0f22d9e6ed96e6326559 Mon Sep 17 00:00:00 2001 From: seiyu Date: Mon, 30 Oct 2023 17:46:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=BF=9E=E6=8E=A5PLC?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cigarette/PLC/PLCDevice.cpp | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Cigarette/PLC/PLCDevice.cpp b/Cigarette/PLC/PLCDevice.cpp index 20d95aa..58a23f2 100644 --- a/Cigarette/PLC/PLCDevice.cpp +++ b/Cigarette/PLC/PLCDevice.cpp @@ -11,22 +11,30 @@ modbus_t * g_modbus = NULL; //Modbus TCP bool PLCDevice::init_plc(PLCDevice* PLCptr) { - const char* comport= g_sys_conf.ComPort.data(); + // modbus_connect() 建立连接,成功返回0,错误返回-1 + // modbus_new_rtu 生成RTU的连接,建立成功则返回指向modbus_t结构的指针,否则将返回NULL/0 + + const char* comport = g_sys_conf.ComPort.data(); qDebug() << "COM:" << comport; //连接PLC g_modbus = modbus_new_rtu(comport, 9600, 'N', 8, 1); - modbus_set_debug(g_modbus, 0); + modbus_set_debug(g_modbus, 0); // 用flag设置debug调试标志位,flag=1时显示modbus消息的字节 + modbus_set_response_timeout(g_modbus, 1, 0); // 设置响应超时 + modbus_connect(g_modbus); + modbus_set_slave(g_modbus, 1); // 设置从站id - modbus_set_response_timeout(g_modbus, 1, 0); - if (g_modbus && modbus_connect(g_modbus) == -1) { + uint8_t data; + int ret = modbus_read_bits(g_modbus, 30000, 1, &data); + if (g_modbus && ret == -1) { PLCptr->g_plc_ok = false; } else { - modbus_set_slave(g_modbus, 1); + PLCptr->g_plc_ok = true; } return true; } + bool PLCDevice::disconnect_plc(void) { if(g_modbus) @@ -36,6 +44,7 @@ bool PLCDevice::disconnect_plc(void) } return true; } + int PLCDevice::write_bit_2_plc(int addr, int value) { if (g_plc_ok)