C# EasyModbus xktComm Modbus 例子

当然先要在NuGet按照相应的dll

            //不是ModbusRTU报文,在RTU报文前面加了4个字节,transactionIdentifier,protocolIdentifier,00 01 00 00 00 06 01 03 00 64 00 02
            EasyModbus.ModbusClient modbusClient = new ModbusClient("127.0.0.1",502);
            modbusClient.NumberOfRetries = 3;//重试次数
            modbusClient.UnitIdentifier = 2;//站号
            modbusClient.Connect();
            int[] intValue = modbusClient.ReadHoldingRegisters(100,2);//读保持寄存器,相当于功能码03,长度为1代表读2个字节,1个字
            modbusClient.Disconnect();
            float floatResult = ModbusClient.ConvertRegistersToFloat(intValue,0);//0为LowHigh 1为HighLow
            textBox1.Text = floatResult.ToString();

以下用的库是xktComm

            xktComm.ModbusRtuOverTCP modbusRtuOverTCP = new xktComm.ModbusRtuOverTCP();
            modbusRtuOverTCP.ConnectTimeOut = 500;
            bool connect= modbusRtuOverTCP.Connect("127.0.0.1","502");
            byte[] resultByte=modbusRtuOverTCP.ReadKeepReg(1,100,1);//序列是RTU,不是TCP,如01 03 00 64 00 01 C5 D5
            byte[] resultReverse = new byte[2]
            {
                resultByte[1],
                resultByte[0]
            };
            int result = BitConverter.ToUInt16(resultReverse, 0);
            modbusRtuOverTCP.DisConnect();
            textBox2.Text = result.ToString();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值