+-

这个问题的灵感来自在这里找到的问题和答案:
Passing a Command to a Comm Port Using C#’s SerialPort Class
Passing a Command to a Comm Port Using C#’s SerialPort Class
该问题本身回答了我遇到的一些问题,但为我提出了其他一些问题.演示中的答案如下:
var serialPort = new SerialPort("COM1", 9600);
serialPort.Write("UUT_SEND \"REMS\\n\" \n");
用于基本的串行端口使用.还要注意以下几点:要获取任何响应,您必须挂钩DataReceived事件.
我的问题如下.我必须使用DataReceived事件还是可以使用serialPort.ReadLine? serialPort.ReadLine的确切功能是什么?我还需要在应用程序中使用serialPort.Open()和serialPort.Close()吗?
最佳答案
您可以在 MSDN documentation中找到有关属性和用法的不错说明,这是一个小示例:
void OpenConnection()
{
//Create new serialport
_serialPort = new SerialPort("COM8");
//Make sure we are notified if data is send back to use
_serialPort.DataReceived += _serialPort_DataReceived;
//Open the port
_serialPort.Open();
//Write to the port
_serialPort.Write("UUT_SEND \"REMS\\n\" \n");
}
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//Read all existing bytes
var received = _serialPort.ReadExisting();
}
void CloseConnectionOrExitAppliction()
{
//Close the port when we are done
_serialPort.Close();
}
点击查看更多相关文章
转载注明原文:C#SerialPort类的用法 - 乐贴网