问题描述
这个问题是灵感都在这里找到了问题的答案:Passing一个命令,一个通信端口使用C#的SerialPort类
This question is inspired by both the question and answer found here:Passing a Command to a Comm Port Using C#'s SerialPort Class
这个问题本身回答了几个问题,我有,但对我提出的一些其他问题。在示范的答案如下:
The question itself answered a few problems I had but raised a few other questions for me. The answer in the demonstration is as follows:
var serialPort = new SerialPort("COM1", 9600);
serialPort.Write("UUT_SEND \"REMS\\n\" \n");
有关基本的串行端口的使用。另外,请注意这一点:要得到任何答复,你将不得不挂钩DataReceived事件检索的
For basic serial port usage. Also make note of this: To get any responses you will have to hook the DataReceived event.
我的问题如下。我一定要使用 DataReceived事件检索
或者我可以使用 serialPort.ReadLine
?什么是 serialPort.ReadLine
的确切功能?另外,我需要使用 serialPort.Open()
和 serialPort.Close()
在我的应用程序?
My questions are as follows. Do I have to use the DataReceived event
or can I use serialPort.ReadLine
? What's the exact function of serialPort.ReadLine
? Also do I need to use serialPort.Open()
and serialPort.Close()
in my application?
推荐答案
您可以找到物业在的,这里是一个小例子:
You can find a nice description of the properties and usage in the MSDN documentation and here is a small example:
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类的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!