I'm new to C#, but have been doing embedded programming for years. I have
an application that talks to an embedded radio on the serial port of my PC.
I have most of the application running pretty well, but if I click a button
before the radio sends its response from the previous command, things get
ugly. I need the application to "lock" waiting on a response from the
serial port before accepting any more commands be sent.
I found the following on the web, but it locks everything including
serialport.readexisting(). I see the command result only after this routine
times out and returns control. I'm obviously doing something wrong. I
don't know exactly how this code works which is part of the problem.
I'm trying to do the following:
send serial command to the Radio (via serialPort)
wait until I get a result back from the radio before allowing any more data
sent to the serial port
I also need a programmable timeout so it doesn't get hung forever
What I have (that doesn't work) is below. Everything in the do-while loop
is what I found on the web. I'm still trying to work out how it works or
doesn't work in this case. Please forgive the messiness. I've been
experimenting with this for several days now.
Thanks for the help!
Scott
private Int16 WaitForResponse(string stringModem, string s, int
timeout)
{
DateTime startTime = DateTime.Now;
int remainingTime = timeout;
bool receivedChars;
object _receiveCharEvent = new Object();
richTextBoxResult.Text = "";
try
{
serialPort.Write(stringModem);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return -1;
}
do
{
lock (_receiveCharEvent)
{
// _receiveBuffer.Append(serialPort.ReadExisting());
// trims the nulls off..since there seems to be a
character
// coming in from the Radio at the beginning of each
command result.
// _receiveBuffer.Replace('\r', '_');
// The radio has a habit of sending a LOT of CR's and LF's
// Need to prune these to make it parseable
richTextBoxResult.Text += serialPort.ReadExisting();
richTextBoxResult.Text.Trim('\r', '\n');
if(richTextBoxResult.Text.Contains(s))
{
return 0;
}
// I have NO idea how Monitor.Wait works
// or if this is what I should even be using
if (0 < remainingTime)
{
// ????? receivedChars =
Monitor.Wait(_receiveCharEvent, remainingTime);
receivedChars = Monitor.Wait(_receiveCharEvent,
remainingTime);
remainingTime = timeout - (int)((DateTime.Now -
startTime).TotalMilliseconds);
}
else
{
receivedChars = false;
}
}
} while (receivedChars);
return -1; // error
}