我用C#编写了一段简单的代码,通过modbus协议(modbus )读写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]);}
}
}
}发布于 2022-06-09 07:19:50
我也做过一个类似的项目,
您可以参考以下readme.md说明
Modbus服务器/客户端
用HslCommunication实现Modbus主/从机
https://stackoverflow.com/questions/16588759
复制相似问题