2

我用 C# 编写了一段简单的代码,通过 modbus 协议(modbus RTU)读取和写入 plc,我的笔记本电脑是主机,plc 是从机。我使用了我在网上找到的 modbus dll。代码工作正常。

我的问题是我现在需要把它变成一个 Windows 服务。我对此做了一个简单的教程并做了一个基本的服务。但是当我试图将它与 modbus 代码集成时,我没有成功。C# 对我来说很新,还有很多我不清楚的东西。如果有人可以建议将我的 modbus 代码转换为服务的最佳方法,我将非常感激,即使他们可以提供某种类型的注释良好的模板。C# modbus 代码如下。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//using System.Data;
using Modbus.Data;
using Modbus.Device;
using Modbus.Utility;
//using System.ServiceProcess;
using System.Collections;

namespace Simple_modbus_write
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            SerialPort port = new SerialPort("COM6");

            // configure serial port
            port.BaudRate = 9600;
            port.DataBits = 8;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;
            port.Open();

            // create modbus master
            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
            byte slaveId = 1;
            ushort outputAddress = 2; // this is the address of the first output of the plc
            ushort inputAddress = 0; // this is the address of the first input of the plc
            ushort numRegisters = 2;


            // write to three coils
            master.WriteMultipleCoils(slaveId,outputAddress, new bool[]{true});

            // delay of 10 seconds
            Thread.Sleep(10000);


            // read the inputs of the plc
            bool[] plc_input = master.ReadInputs(slaveId,inputAddress,numRegisters);


            for (int i=0; i<plc_input.Length;i++){

                // write the status of the plc inputs (i.e. true or false)
                Console.WriteLine(" the input at " + i + " value is:" + plc_input[i]);}



            // if the input is false (i.e. switch is off) then turn off the output
            if(plc_input[0]==false && plc_input[1]==false)

            {
                master.WriteMultipleCoils(slaveId,outputAddress, new bool[]{false});
            }



            // at the end read the status of the output and print its status to the screen
            bool[] plc_output = master.ReadCoils(slaveId,outputAddress,numRegisters);

            for (int j=0; j<plc_input.Length;j++){

                Console.WriteLine("the output at " + j + " value is:" + plc_output[j]);}

        }
    }
}
4

0 回答 0