This I know is a bit of a cludgy method but it is the only one I have to effectivly hold the reading code until there is a reply with out locking up windows it is called by Write_Board("hello");
which will send hello out of myComPort with a \n & \r the timer NoDataAtPort is atimer with a 10 second time out which should be suitable if the device has died or been taken away,
private string Write_Board(string Data_To_Board)
{
Pause.Start();
myComPort.Write(Data_To_Board + (char)10 + (char)13);
{
while (Reply_Status == (int)REPLY.NO_REPLY)
{
NoDataAtPort.Enabled = true;
}
NoDataAtPort.Enabled = false;
if (Reply_Status == (int)REPLY.TIMEOUT_REPLY)
{
Data_From_Board = "TIMEOUT\n";
Pause.Stop();
}
else if (Reply_Status == (int)REPLY.YES_REPLY)
{
Pause.Stop();
try
{
InputData = myComPort.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
}
else if (InputData == String.Empty)
{
return (null);
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Error Caught!!" );
}
}
else
{
Cursor.Current = Cursors.No;
Reply_Status = (int)REPLY.NO_REPLY;
}
}
Data_From_Board = Data_From_Board + "|||";
return (Data_From_Board);
}
----------------
also I am using another timer to see if there is any data at the port also Pause is a timer 100 ms time out (I'm starting to wonder if I have toxic timer syndrome!)
----------------
public int WaitForData(int Timeout)
{
Stopwatch sw = Stopwatch.StartNew();
sw.Start();
this.Invoke(new MethodInvoker(delegate()
{
rtbIncomingData.Text += ReplyData;
}));
while (sw.ElapsedMilliseconds < Timeout && myComPort.BytesToRead > 0)
{
Thread.Sleep(1);
}
int elapsed = (int)sw.ElapsedMilliseconds;
sw.Stop();
return elapsed;
}
This method is one I have use multiple times with success I did developed it in a caffine fuel weekend to prevent bits of data replies going missing ReadExisting() was chosen as the read method (I have used it with ReadLine() when I was sure there was a \n in the data) as there is no documentation for this hardware and the PSION appears to strip everything but the data and I can't get any data to appear using it while read existing I do.
Any ideas: