ios - 将线圈(位)写入 Modbus PLC

标签 ios c swift4 modbus

我在写入 Schneider Modicon M221 PLC 时遇到问题。 我正在使用 Swift wrapper LibModbus周围库(在 C 中)。 我可以读取位和寄存器没有问题 - 只是似乎无法写入它们 - 尽管我从设备收到“成功”响应。

这就像使用函数 05 将“true”写入位 0 一样简单。

Swift(4) 调用:

@objc func writeToPLC() {

    swiftLibModbus.writeBit(address: 0, status: true,
                            success: {
                                    print("writeBit Success")

    },
                            failure: { (error:NSError) in
                                print("Error in WriteBit")

    })

}

在 Swift/ObjC SwiftLibModbus 包装器中写入此函数:

func writeBit(address: Int32, status: Bool, success: @escaping () -> Void, failure: @escaping (NSError) -> Void) {
    modbusQueue?.async {
        if modbus_write_bit(self.mb!, address, status ? 1 : 0) >= 0 {
            DispatchQueue.main.async {
                success()
            }
        } else {
            let error = self.buildNSError(errno: errno)
            DispatchQueue.main.async {
                failure(error)
            }
        }
    }
}

写入库中的这些 C 函数:

int modbus_write_bit(modbus_t *ctx, int addr, int status){
return write_single(ctx, _FC_WRITE_SINGLE_COIL, addr,
                    status ? 0xFF00 : 0);
}

然后:

static int write_single(modbus_t *ctx, int function, int addr, int value){
int rc;
int req_length;
uint8_t req[_MIN_REQ_LENGTH];

req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req);

rc = send_msg(ctx, req, req_length);
if (rc > 0) {
    /* Used by write_bit and write_register */
    uint8_t rsp[_MIN_REQ_LENGTH];
    //printf("Print %s, %s, %d ", req, rsp, rc);
    rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
    if (rc == -1)
        return -1;

    rc = check_confirmation(ctx, req, rsp, rc);

}

return rc;}

_FC_WRITE_SINGLE_COIL常量为0x05
_MIN_REQ_LENGTH 常量为 12

运行时控制台显示“writeBit Success”,但位状态保持不变。

开始怀疑它是否是 Schneider 的专有产品。

其他人有这方面的经验吗?

最佳答案

好吧,我发现我做错了什么。我没有正确设置单位 ID。它应该是“255”,而却是“1”。

这是 SoMachine 中设置的屏幕截图,以防其他人发现自己处于相同情况:

enter image description here

关于ios - 将线圈(位)写入 Modbus PLC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47616167/

相关文章:

ios - 如何在 ios 中使用地址显示谷歌地图?

ios - SWIFT 中的元组数组作为函数的参数

c - 如何将数组的后半部分逐个合并到前半部分?

Codevision AVR 使用 TWI 访问外部 eeprom 24c02B

swift - 从未调用完成处理程序

realm - 在 Xcode 9 中使用 RealmSwift 3.1.1 时出现多个警告

ios - 在 Map Pin Xcode 中调整 leftCalloutAccessoryView 的 UIImageView 大小

ios - Swift 全局变量不更新

代码块中的编译选项

ios - 如何识别哪个 UITextField 被 textFieldDidChange 更改了