C++ modbus TCP 协议跟PLC通信

modbus 用的是git上的开源代码,地址:https://github.com/stephane/libmodbus

讲一下基本使用(给指定地址发送 on/off命令以及读取):

modbus_t *ctx = NULL;
ctx = modbus_new_tcp("127.0.0.1", 502);//填写的是plc的ip、port
if (ctx == NULL)
{
    cout << "Unable to allocate libmodbus context" << endl;
    return -1;
}

//modbus_set_debug(ctx, TRUE);

if (modbus_connect(ctx) == -1)
{
    cout << "Connection failed: " << modbus_strerror(errno) << endl;
    modbus_free(ctx);
    return -1;
}


/* WRITE BIT */

int rc = modbus_write_bit(ctx, addr, value); //addr: 0x6000 value:true

if (rc != 1)

{

    cout <<"ERROR modbus_write_bit  "<< rc << endl;

}

uint8_t tab_rp_bits[4] = { 0 };
rc = modbus_read_bits(ctx, addr, 1, tab_rp_bits);

if (rc != 1)

{

    cout <<"ERROR modbus_read_bits  "<< rc << endl;

}

/* Close the connection */
modbus_close(ctx);
modbus_free(ctx);
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值