这个问题的灵感来自于此处的问题和答案: 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 event
还是可以使用serialPort.ReadLine
? serialPort.ReadLine
的确切功能是什么?我还需要在我的应用程序中使用serialPort.Open()
和serialPort.Close()
吗?
答案 0 :(得分:3)
您可以在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();
}