c#-NModbus-tcp-ReadCoils-代码实验

该代码示例展示了如何通过Modbus Ip Master库连接到本地IP地址为127.0.0.1的设备,并从起始地址0读取10个线圈的状态。读取的数据以bool数组形式返回,并打印出来。

1.概要

bool[] inputs = master.ReadCoils(1, startAddress, numInputs);

2.代码 

using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        static void Main(string[] args)
        {
            test1();
            Console.ReadKey();
        }
        static private void test1()
        {
            IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
            using (TcpClient client = new TcpClient(address.ToString(), 502))
            {
                client.SendTimeout = 1;
                ModbusIpMaster master = ModbusIpMaster.CreateIp(client);
                ushort startAddress = 0;
                ushort numInputs = 10;
                bool[] inputs = master.ReadCoils(2, startAddress, numInputs);
                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}");
                }
            }
        }

    }
}

3.运行结果

 服务端生成的报文

0001      0000     0006  02       01      0000     000A
事务标识   协议标识  长度  单元标识  功能码   起始地址  读线圈的数量
ReadCoils                (1,              0,       10)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值