. NET 을 사용한 MODBUS TCP 통신 예제 코드

freeFree Technical Resource

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

. NET 을 사용한 MODBUS TCP 통신 예제 코드

Modbus RTUマスター简单读書き込み操作。

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);
		}
	}
}

Modbus-TCP Client 简单读書き込み操作。

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);
        }
    }
}

从Modus-Serve読み取り值,并将值发布到MQTT代理

 class Program
    {
        static void Main(string[] args)
        {
            EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient("127.0.0.1", 502);
            //Increase the Connection Timeout to 5 seconds
            modbusClient.ConnectionTimeout = 5000;
            //We create a Log File. This will also active the Event logging 
            modbusClient.LogFileFilename = "test.txt";
            //The Messages sent to the MQTT-Broker will be retained in the Broker. After subscribtion, the client will automatically
            마지막으로 저장 된 메시지를 수신 합니다 . Rece ive the last reta ined message .기본적으로 Ret in - Flag 는 F AL SE -> 메시 지가 유지 되지 않습니다 .
            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 ' '
                " Pass word " 및 " U ser name " 은 사용자 와 암호 를 필요로 하는 브 로 커 에 연결 하는 데 사용할 수 있습니다 .기본적으로 the 
                M Q TT - 브 로 커 포 트는 188 3 입니다 .
                www.mqtt-dashboard.com int
                System . Th re ading . Thread . Sleep (1 000)
            }
            mod bus C li ent . Dis conne ct () ;
            Con sole . Read K ey () ;
        }
    }

Mode - Server 에서 값을 자동 으로 폴 링 하여 M Q TT 에이 전 트에 게시 합니다 .

        static void Main(string
        {
            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
            easy Mod bus 2 M q tt . M q tt U ser N ame = " sr 55 5 ";
            easy Mod bus 2 M q tt . M q tt Pass word = " ** ** ** ** ** ** ** ** **
            easy Mod bus 2 M q tt . M q tt B rok er Port = 1897 2;
            broker.hivemq.com//easyModbus2Mqtt.MqttBrokerAddress
            192.168.178.101//easyModbus2Mqtt.MqttBrokerAddress
            m21.cloudmqtt.com easyModbus2Mqtt.MqttBrokerAddress = "
            127.0.0.1 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.Hysteresis = new int
            readOrder.Unit = new string
            readOrder.Scale = new float
            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 에이 전 트에 게시 합니다 .

   클래 스 프로그램
    {
        static void Main(string
        {
            프로그램 application = new Program ();
            application . start Ser ver () ;

        }

        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 ();
            mod bus Ser ver . M q tt Ro ot Top ic = " ex ample mod bus ser ver ";
            www.mqtt-dashboard.com 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);
        }
    }

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 *.