C# SerialPort Class Usage

亡梦爱人 提交于 2019-12-23 19:39:30

问题


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");

For basic serial port usage. Also make note of this: To get any responses you will have to hook the DataReceived event.

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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/17552268/c-sharp-serialport-class-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!