Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SerialPort

Status
Not open for further replies.

gplusplus

Programmer
Jan 17, 2007
30
0
0
US
I have a serial port connection... The serial port has the data received event registered with it.

I have an array of data. This data is to be written to a serial port.

When the user hits the start button a new thread is created and this loops through each index of the array and on each iteration, the data is written to the serial port. I sleep for 250ms while waiting for a response back. If i get a response i go to the next line. If i dont i resend.
This all works just fine...but....

i want instead of sleeping for a static 250ms be able to stop sleeping when the data receieved event is fired with a message.

So i tried this:


USING A Thread.Sleep(ms);

// this.message_received is set to true when data received
// event of the serial port is fired

// this.timeout_ms = 250


Code:
int counter = 0;

while (!this.message_received && counter < this.time_out_ms)
{
   Application.DoEvents();
   Thread.Sleep(1);
   Console.WriteLine("Sleeping: " + counter.ToString());
   counter++;
}

Or using a TIMER:

Code:
// this.wait_release is set to true on a tick of the timer // every ms

// this.message_received is set to true when data received
// event of the serial port is fired

// this.timeout_ms = 250

int counter = 0;

while (!this.message_received && counter < this.time_out_ms)
{
   Console.WriteLine("Sleeping: " + counter.ToString());
   while(!this.wait_release)
   {
      Application.DoEvents();
   }
   this.wait_release = false;
                
   counter++;
}


Basically what happens here is the data receive is not consistent anymore...before when i would just sleep for a static 250ms it would send once and respond once for each line.... with these two options above sometimes it has to send the line 3 times before i get anything back.... any ideas ?

I would like to not use the Thread.Sleep way but any ideas i would really appreciate.





 
The normal way of doing this is to create a System.Threading.AutoResetEvent in the data recieved event and have the sending code block on it rather than using sleep. Something like this:

Code:
private void ControlLoop()
        {
            while (true)
            {
                // Do your write

                are.WaitOne();

                // Read the data
            }
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            are.Set();
        }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top