I have an equipment which sends data continuously when an operation is performed. I use RS232 to communicate through the COM port. I am able to read and write the data but reading the data is not good.
To understand better consider the following scenario:
I send “H” command and in return the data responds with “HELLO” continuously line after line. After 10 seconds it stops and ends the data with “BYE” message. Using a do..while loop I am able to read the data but then the UI is unresponsive while reading the data. I have a class named serialCom.cs which establishes the connection, writes data and reads data. While reading, the data is sent to Form1.cs to display in the UI. While reading, I am able to capture the data but not displayed in the UI as the UI is unresponsive. In fact, the UI only displays the “BYE” message as the read is stopped and UI becomes responsive.
What is best way to read serial data? any simple logic or syntax would be helpful?
namespace ReadSerialData
{
public class serialCom
{
private SerialPort serialPort;
public delegate void sendResponseData(string data);
public event sendResponseData m_resData;
public serialCom()
{
serialPort = new SerialPort();
}
public bool OpenPort(string comPortName, int baudRate)
{
// This contains open port logic
// setting all the properties to open the port
// portname, baudrate, parity, databits
}
public bool closePort()
{
// This function closes the port
}
public void writeCommand(string cmd)
{
serialPort.Write(command);
}
public void ReadSerialData()
{
if(!SerialPort.IsOpen) {
MessageBox.Show("Serial port not open");
} else {
//Read serial data code here
do {
byte[] buffer = new byte[4096];
int bytesRead = 0;
} while();
}
}
}
}
giri lakshman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.