我试图通过RS232通过modbus与PLC通信,但它只是说我的消息应包含至少6个字节的数据。 首先,我很抱歉,我似乎总是在努力解决代码输入...,我使用相同的类进行TCP / IP modbus连接似乎工作得很好,现在我试图通过RTU RS232 我在编辑中添加了我的两个课程,提前感谢我希望有人可以帮助我。
namespace ConsoleApplication2
{
class Program
{
public static ModBusDriver modbusDriver;
static void Main(string[] args)
{
SerialPort port = new SerialPort("COM1");
port.BaudRate = 38400;
port.DataBits = 8;
port.ReadTimeout = 600;
port.WriteTimeout = 600;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
modbusDriver = new ModBusDriver(port);
modbusDriver.connect(1);
byte slaveAddress = 1;
modbusDriver.WriteMultipleCoils(slaveAddress, 8193, new bool[6] { false, false, false, false, false, false });
Console.WriteLine("done");
Console.Read();
}
Modbusdriver.cs
using Modbus.Device;
using System;
using System.IO.Ports;
using System.Net.Sockets;
using System.Threading;
namespace CoCoSModBusDriver
{
// based on nmodbus4:
// -https://github.com/NModbus4/NModbus4
class ModBusDriver
{
public int connected;
private bool gotClient = false;
public IModbusSerialMaster modbusConnector;
public SerialPort serialPort;
public ModBusDriver(SerialPort port)
{
serialPort = port;
modbusConnector = ModbusSerialMaster.CreateRtu(port);
}
public void connect(int retries)
{
int retryCounter = 0;
while (retryCounter < retries || retries == -1)
{
try
{
serialPort.Open();
}
catch (Exception ex)
{
retryCounter++;
Thread.Sleep(5000);
}
}
}
public void WriteMultipleCoils(byte slaveAdress, ushort startAdress, bool[] data)
{
try
{
modbusConnector.WriteMultipleCoils(slaveAdress, startAdress, data);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
答案 0 :(得分:0)
您缺少请求中的从属地址。从IModbus主接口:
/// <summary>
/// Writes a sequence of coils.
/// </summary>
/// <param name="slaveAddress">Address of the device to write to.</param>
/// <param name="startAddress">Address to begin writing values.</param>
/// <param name="data">Values to write.</param>
void WriteMultipleCoils(byte slaveAddress, ushort startAddress, bool[] data);
答案 1 :(得分:0)
您应该使用ModbusSerialMaster类。在mesta自动化主页上有一个很好的例子。