Reputation: 1540
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?
Upvotes: 3
Views: 1751
Reputation: 2769
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();
}
Upvotes: 3