I am trying to write a C # program in Visual Studio 2010 that communicates with a microcontroller through a serial connection. I can read and write normally to the port, I just don’t know how to make the send method wait until all the data from the previous send command is received before they are executed. I implemented a processed data handler so that it determines when the necessary amount of data was requested on the serial port. I just need to know how to get this to tell the send method that this port is free.
I planned to use a mutex, but I believe that the problem is not multithreaded. The same stream sends the lines to the serial port one by one, and the data received in response to the first request contradicts the second request.
In addition, if communication is performed by a single thread, will this thread wait for the processed data handler to not execute?
(both methods are in the same class)
My method of sending data:
public void send(String s)
{
sp.Write(s + "\r");
}
My processed data handler:
private void dataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string tmp;
tmp = sp.ReadExisting();
readBuffer += tmp;
if (firmwareFlag)
{
if (readBuffer.EndsWith("\n"))
{
firmwareFlag = false;
dataReady(this, new CustomEventArgs(readBuffer, "firmware"));
readBuffer = "";
}
}
else if (parameterFlag)
{
if (System.Text.RegularExpressions.Regex.IsMatch(readBuffer, "K90", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
parameterFlag = false;
dataReady(this, new CustomEventArgs(readBuffer, "parameters"));
readBuffer = "";
}
}
else
{
dataReady(this, new CustomEventArgs(readBuffer, null));
readBuffer = "";
}
}
source
share