C# modbus ascii通讯示例
时间: 2024-10-09 14:09:48 浏览: 65
在C#中,Modbus ASCII通信通常用于简单的串行通信,它基于ASCII字符编码来传输数据。以下是一个简化的C# Modbus ASCII通信示例,使用了`System.IO.Ports.SerialPort`类:
```csharp
using System;
using System.IO.Ports;
class Program
{
static void Main(string[] args)
{
// 创建SerialPort实例
SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
try
{
// 打开串口
port.Open();
// 发送请求
string request = "03 00 00"; // Function Code (FC) 3 (Read Holding Registers), Start Address 0, Number of Registers 1
byte[] bytesToWrite = ASCIIEncoding.ASCII.GetBytes(request);
port.Write(bytesToWrite);
// 接收响应
byte[] bytesReceived = new byte[1];
port.ReadTimeout = 500; // 设置读取超时时间
if (port.BytesToRead > 0)
{
port.Read(bytesReceived, 0, 1);
Console.WriteLine($"Response: {BitConverter.ToString(bytesReceived)}");
}
else
{
Console.WriteLine("No response received.");
}
// 关闭串口
port.Close();
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
阅读全文