3

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?

3
  • 1
    The exact function of ReadLine can be found here msdn.microsoft.com/en-us/library/… . Basically it will read up to the first occurrence of a NewLine Value. There is also a ReadExisting which will get all the remaining contents of the stream in the buffer back as a string. You dont HAVE to use dataRecieved event, but its a nice event to subscribe to, to know when data has come and you can use which ever method you want to access the data. See here msdn.microsoft.com/en-us/library/… and view the methods. Commented Jul 9, 2013 at 15:44
  • 1
    As to the Open and Close, yes and yes! If you don't open the connection to the port how can you expect to read data from it. Also its always good practice to close your connections once you are through with them. Commented Jul 9, 2013 at 15:47
  • Also, SerialPort implements IDisposable, so you should either wrap its lifetime in a using block or have your containing class also implement IDisposable and Dispose() it using the "disposable pattern". Note, then, your containing class should be in a using block, etc. Commented Jul 9, 2013 at 15:57

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.