By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,180 Members | 1,012 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,180 IT Pros & Developers. It's quick & easy.

SerialPort - How to send a message and await a reply?

P: 1
Iíve written a program in C# which scans a network of devices connected to the serial port.
I use a thread to send a message addressed to a external device then I use ManualResetEvent.WaitOne(200) to pause the thread and wait for a reply. If a correct response is received from the serial port, an event is fired which restarts the scan thread with ManualResetEvent.Set(). When a correct response is received or the ManualResetEvent times out, I increment the address and scan for the next device.

This works fine until another program loads up the processor, which can cause the SerialPort DataReceived event to be delayed by over 2 seconds and the ManualResetEvent to time out therefore missing a valid response from a device.

Pseudo code:

Expand|Select|Wrap|Line Numbers
  1. // Scan network method
  2. {
  3.     private void  Scan (void)
  4.     {
  5.         MessageFilter.MessageFilterEvent += new MessageFilter.MessageReceivedHandler(MessageFilter_MessageFilterEvent);
  6.  
  7.         for(int address = 1; address <= 127; address ++)
  8.         {
  9.     send serial message();
  10.     ManualResetEven.WaitOne(200);
  11.     if(message was received)
  12.     {
  13.         Device found
  14.     }
  15.     ManualResetEvent.Reset();
  16.        }
  17.     }
  18.  
  19.     private void MessageFilter_MessageFilterEvent(object sender,MessageReceivedEventArgs e)
  20.     {
  21.         ManualResetEvent.Set();
  22.     }
  23. }
  24.  
  25. // SerialPort received event
  26. private void Serial_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  27. {
  28.     Process data
  29.     if(this is a valid message)
  30.     {
  31.         Trigger MessageReceivedEvent event
  32.     }
  33. }
  34.  
  35. // Valid message received event
  36. private void MessageReceivedEvent(object sender, MessageReceivedEventArgs e)
  37. {
  38.     // Filter messages
  39.     if(received message == required message)
  40.     }
  41.         Trigger MessageFilter_MessageFilterEvent event
  42.     }
  43. }

Can anyone think of a better way of writing the send Ė await response process that doesnít rely on processor speed?

Thanks in advance,
James
Mar 13 '10 #1
Share this Question
Share on Google+
1 Reply


tlhintoq
Expert 2.5K+
P: 3,525
TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.
Mar 13 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.