您好,我正在用 C# 编写一个应用程序,以通过 rs232(com) 端口连接到设备。我需要发送一个“读”命令来从中读取数据,并发送一个“写”命令来向它发送一些数据。
我在这里和其他一些网站上阅读了一些文章,我知道在 C# 中定义串行端口时有一些方法。
但我的问题是,我应该关心 DTR、RTS 等吗? 它们是做什么用的?我该如何使用它们?
最佳答案
只是为了给您一个想法,这是一个非常简单的函数,它将命令作为 byte
数组写入串行上,并从串行端口读取相应的输入(在本示例中,我只读取了第四个字节从串口读取的值):
private string ReadFromSerial()
{
try
{
System.IO.Ports.SerialPort Serial1 = new System.IO.Ports.SerialPort("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
Serial1.DtrEnable = true;
Serial1.RtsEnable = true;
Serial1.ReadTimeout = 3000;
var MessageBufferRequest = new byte[8] { 1, 3, 0, 28, 0, 1, 69, 204 };
var MessageBufferReply = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
int BufferLength = 8;
if (!Serial1.IsOpen)
{
Serial1.Open();
}
try
{
Serial1.Write(MessageBufferRequest, 0, BufferLength);
}
catch (Exception ex)
{
logEx(ex);
return "";
}
System.Threading.Thread.Sleep(100);
Serial1.Read(MessageBufferReply, 0, 7);
return MessageBufferReply[3].ToString();
}
catch (Exception ex)
{
logEx(ex);
return "";
}
}
关于c# - 如何从串口读取数据并写入串口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17964864/