C# NMODBUS

string ipAddress = "192.168.16.201";
            int tcpPort = 3084;
            TcpClient tcpClient = new TcpClient();
            IAsyncResult asyncresult = tcpClient.BeginConnect(ipAddress, tcpPort, null, null);
            asyncresult.AsyncWaitHandle.WaitOne(1000);
            if (!asyncresult.IsCompleted)
            {
                tcpClient.Close();
                Console.WriteLine("Cannot to Connect Server");
                return;
            }

            ModbusIpMaster master = ModbusIpMaster.CreateIp(tcpClient);
            // byte slaveID = 1;
            //开始地址为0
            ushort startAddress = 0;
            ushort numOfPoints = 22;
            master.Transport.Retries = 0;
            master.Transport.ReadTimeout = 300;
            try
            {
                ushort[] register = master.ReadHoldingRegisters(1, startAddress, numOfPoints);
                float temperatureValue = Convert.ToSingle(register[14]) / 10;
                float humidityValue = Convert.ToSingle(register[15]) / 10;
                Console.WriteLine("温度:" + temperatureValue + "湿度:" + humidityValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

你可能感兴趣的:(C#)