美文网首页
how to use modbus in C#

how to use modbus in C#

作者: 老中医167788 | 来源:发表于2024-05-12 15:12 被阅读0次

    Github simples

    Slave

    using NModbus;
    using System.Net;
    using System.Net.Sockets;
    
    Console.Title = "ModbusSlave";
    
    
    byte slaveId = 1;
    int port = 502;
    IPAddress address = new IPAddress(new byte[] { 127, 0, 0, 1 });
    
    // 创建并启动TCP从站
    TcpListener slaveTcpListener = new TcpListener(address, port);
    slaveTcpListener.Start();
    
    var factory = new ModbusFactory();
    var network = factory.CreateSlaveNetwork(slaveTcpListener);
    
    IModbusSlave slave = factory.CreateSlave(slaveId);
    
    network.AddSlave(slave);
    
    await network.ListenAsync();
    
    
    
    // 创建主站
    TcpClient masterTcpClient = new TcpClient(address.ToString(), port);
    IModbusMaster master = factory.CreateMaster(masterTcpClient);
    
    ushort startAddress = 7165;
    master.WriteMultipleRegisters(1, startAddress,new ushort[] {1,2 });
    
    // 清理
    masterTcpClient.Close();
    slaveTcpListener.Stop();
    
    // output
    // Register 100=0
    // Register 101=0
    // Register 102=0
    // Register 103=0
    // Register 104=0
    
    Console.ReadKey(true);
    

    Master

    using System.Net.Sockets;
    using NModbus;
    
    Console.Title = "ModbusMaster";
    
    using (TcpClient client = new TcpClient("127.0.0.1", 502))
    {
        var factory = new ModbusFactory();
        IModbusMaster master = factory.CreateMaster(client);
    
        byte slaveId = 1;
        ushort startAddress = 7165;
        ushort numInputs = 2;
    
        //master.WriteMultipleRegisters(slaveId, startAddress, new ushort[] { 1, 2 });
        ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numInputs);
    
        Console.Write($"{startAddress}: {string.Join(" ",registers)}");
    }
    
    Console.ReadKey();
    

    相关文章

      网友评论

          本文标题:how to use modbus in C#

          本文链接:https://www.haomeiwen.com/subject/fgjufjtx.html