EasyModbus TCP. NET 예제 코드

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

EasyModbus TCP. NET 예제 코드

.NET:Modbus-RTU Master Simple Read and Write Operation

using System;
using EasyModbus;
 
namespace ModbusRS485Master
{
	class Program
	{
		public static void Main(string[] args)
		{
			ModbusClient modbusClient = new ModbusClient("COM1");
			//modbusClient.UnitIdentifier = 1; Not necessary since default slaveID = 1;
			//modbusClient.Baudrate = 9600;	// Not necessary since default baudrate = 9600
			//modbusClient.Parity = System.IO.Ports.Parity.None;
			//modbusClient.StopBits = System.IO.Ports.StopBits.Two;
			//modbusClient.ConnectionTimeout = 500;			
			modbusClient.Connect();
			
			Console.WriteLine("Value of Discr. Input #1: "+modbusClient.ReadDiscreteInputs(0,1)[0].ToString());	//Reads Discrete Input #1
			Console.WriteLine("Value of Input Reg. #10: "+modbusClient.ReadInputRegisters(9,1)[0].ToString());	//Reads Inp. Reg. #10
			
			modbusClient.WriteSingleCoil(4,true);		//Writes Coil #5
			modbusClient.WriteSingleRegister(19,4711);	//Writes Holding Reg. #20
			
			Console.WriteLine("Value of Coil #5: "+modbusClient.ReadCoils(4,1)[0].ToString());	//Reads Discrete Input #1
			Console.WriteLine("Value of Holding Reg.. #20: "+modbusClient.ReadHoldingRegisters(19,1)[0].ToString());	//Reads Inp. Reg. #10
			modbusClient.WriteMultipleRegisters(49, new int[10] {1,2,3,4,5,6,7,8,9,10});
			modbusClient.WriteMultipleCoils(29, new bool[10] {true,true,true,true,true,true,true,true,true,true,});
			
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}
	}
}

NET:Modbus-TCP クライアント側は简单读書き込み操作。

namespace ModbusClientApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            ModbusClient modbusClient = new ModbusClient("190.201.100.100", 502);    //Ip-Address and Port of Modbus-TCP-Server
            modbusClient.Connect();                                                    //Connect to Server
            modbusClient.WriteMultipleCoils(4, new bool[] {true, true, true, true, true, true, true, true, true, true});    //Write Coils starting with Address 5
            bool[] readCoils = modbusClient.ReadCoils(9,10);                        //Read 10 Coils from Server, starting with address 10
            int[] readHoldingRegisters = modbusClient.ReadHoldingRegisters(0,10);    //Read 10 Holding Registers from Server, starting with Address 1

            // Console Output
            for (int i = 0; i < readCoils.Length; i++)
                Console.WriteLine("Value of Coil " + (9 + i + 1) + " " + readCoils[i].ToString());
                        
            for (int i = 0; i < readHoldingRegisters.Length; i++)
                Console.WriteLine("Value of HoldingRegister " + (i + 1) + " "+ readHoldingRegisters[i].ToString());            
            modbusClient.Disconnect();                                                //Disconnect from Server
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

从模组サーバー·サーバー読み取り值并将值发布到 MQTT 代理

 class Program
    {
        static void Main(string[] args)
        {
            EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient(
            Conne ction Time out 를 5 초 로 늘 리 십시오 .
            mod bus C li ent . Conne ction Time out = 5000 ;
            우리는 로 그 파일을 만듭니다 .또한 이벤트 로 깅 을 활성화 합니다 . 
            modbusClient.LogFileFilename = 
            M Q TT - Br oker 에 보낸 메시 지는 Br oker 에 보존 됩니다 .가입 후 , 클 라이언 트는 자동 으로
            마지막으로 저장 된 메시지를 수신 합니다 . Rece ive the last reta ined message . By default the Retain-Flag is FALSE -
            mod bus C li ent . M q tt R eta in M ess ages = true ;
            Mod bus TCP 서버 에 연결 하기
            mod bus C li ent . Connect () ;
            while (tr ue)
            {
                서버 에서 두 개의 레 지 스트 리를 읽고 M Q TT - Br oker 에 게시 합니다 .기본적으로 값 이 게시 됩니다 . By default V alu es are published
                기본적으로 우리는 ' e as ym od bus cli ent /' 과 주 소를 게시 합니다 . e . g . ' ' e as ym od bus cli ent / holding reg ister 1 ' '
                // The propery 기본적으로 the 
                M Q TT - 브 로 커 포 트는 188 3 입니다 .
                int[] holdingRegister = modbusClient.ReadHoldingRegisters(60, 2, 
                System . Th re ading . Thread . Sleep (1 000)
            }
            mod bus C li ent . Dis conne ct () ;
            Con sole . Read K ey () ;
        }
    }

모듈 서버 에서 값을 자동 으로 폴 링 하고 M Q TT 에이 전 트에 게시 - 주제 변경

        st atic vo id Main ( string [ ] arg s)
        {
            Easy Mod bus . Easy Mod bus 2 M q tt easy Mod bus 2 M q tt = new Easy Mod bus . Easy Mod bus 2 M q tt ();
            //easyModbus2Mqtt.AutomaticReconnect
            easyModbus2Mqtt.MqttUserName = 
            easyModbus2Mqtt.MqttPassword = 
            easy Mod bus 2 M q tt . M q tt B rok er Port = 1897 2;
            //easyModbus2Mqtt.MqttBrokerAddress
            //easyModbus2Mqtt.MqttBrokerAddress
            easyModbus2Mqtt.MqttBrokerAddress = 
            easyModbus2Mqtt.ModbusIPAddress = 
            easyModbus2Mqtt.AddReadOrder(EasyModbus.FunctionCode.ReadCoils, 2, 0, 200, new string[] { 
            easy Mod bus 2 M q tt . Add Read Or der (E asy Mod bus . Fun ction C ode . Read In put Reg ister s , 2, 0, 200);
            Easy Mod bus . Read Or der read Or der = new Easy Mod bus . Read Or der () ;
            [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ] [ 중 고 ]
            readOrder.Unit = new string[10] {
            read Or der . S cale = new flo at [10] { 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f , 0. 1 f } ;
            read Or der . Quant ity = 10
            read Or der . Start ing Add ress = 10;
            read Or der . Fun ction C ode = Easy Mod bus . Fun ction C ode . Read H old ing Reg ister s ;          
            easy Mod bus 2 M q tt . Add Read Or der (read Or der);
            easy Mod bus 2 M q tt . start () ;
        }

Mod bus - TCP 서버 , 변경 된 값을 M Q TT - Br oker 에 게시 합니다 .

   클래 스 프로그램
    {
        st atic vo id Main ( string [ ] arg s)
        {
            프로그램 application = new Program ();
            application.startServer ();

        }

        public vo id start Ser ver ()
        {
            Easy Mod bus . Mod bus Ser ver mod bus Ser ver = new Easy Mod bus . Mod bus Ser ver ();
            modbusServer.MqttRootTopic = 
            modbusServer.MqttBrokerAddress = 
            mod bus Ser ver . Listen () ;
            mod bus Ser ver . holding Reg ister s C hang ed + = new Easy Mod bus . Mod bus Ser ver . Hold ing Reg ister s C hang ed (hold ing Reg ister s C hang ed);
            Con sole . Read K ey () ;
            
            mod bus Ser ver . Stop L isten ing () ;
        }

        public vo id holding Reg ister s C hang ed (int beginning Add ress , int quant ity)
        {
            Con sole . Write L ine (start ing Add ress);
            Con sole . Write L ine (quant ity);
        }
    }

Easy Mod bus TCP / U DP / R TU . NET 라이 브 러 리 링크 는 이 페이지 에서 다운로드 할 수 있습니다 .

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.