Click here to Skip to main content
15,878,748 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
In my code i have to handle the serial port write, which should be delayed for 1 second.
My code is as follows.

C#
while (bytesRd < byteExpctd)
               {

                   bytesRd += serialPort.Read(Req, bytesRd, byteExpctd - bytesRd);
                   //serialPort.ReadTimeout = 80;
               }
               byteExpctd = (int)Req[1];
               while (bytesRd < byteExpctd)
               {

                   bytesRd += serialPort.Read(Req, bytesRd, byteExpctd - bytesRd);

               }

               if (Req[0] == 0x14 && Req[0] == 0x06)
               {
                   AckMsg[0] = 0x0B;
                   AckMsg[1] = 0x06;
                   AckMsg[2] = 0xA4;
                   AckMsg[3] = CheckSum(AckMsg);
                   serialPort.Write(AckMsg, 0, 5);
               }
               else
               {
                  // code for something
               }
               Thread.sleep(1000);
               RsltMsg[0] = 0x9F;
               RsltMsg[1] = 0x05;
               RsltMsg[2] = 0x19;
               RsltMsg[3] = CheckSum(RsltMsg);
               serialPort.Write(RsltMsg, 0, 3);


How to delay the serial port write for 1 second in c#? I have to introduce a delay of 1 minute between the first and second write. I tried with Thread.Sleep(), but it doesn't make any change. Is there any alternate solution to introduce the delay of 1 minute. I am using custom baud rate of 10,4K. Please help.
Posted
Updated 25-Sep-14 22:21pm
v2
Comments
Leo Chapiro 26-Sep-14 4:26am    
IMHO is the Thread.sleep exactly the right way to do it. How did you detect that it doesn't make any change?
Utheen 26-Sep-14 4:28am    
At the receiving end, it always shows the no response error as there is ReadTimeout of 70 ms.
E.F. Nijboer 26-Sep-14 4:36am    
The problem seems to be the timeout. You would need to setup the serialport again for the 2nd write. You keep it open but the other side stops listening after 70ms, so I would suggest to just reinitialize the connection or change the timeout on the receiving end.
Leo Chapiro 26-Sep-14 4:36am    
LOL: so he did the sleep of 1000 ms! The really problem seems to be that no data will be received!

1 solution

Thread.Sleep(1000); should work fine here. Try a minute and see how it goes. Thread.Sleep(1000 * 60);

Otherwise you could check out timers.
http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx[^]

Good luck!
 
Share this answer
 
Comments
Oshtri Deka 26-Sep-14 4:31am    
Thread.Sleep(N) is sufficient. Solution with timer is IMHO overkill and only adds to complexity.
Anyway, my 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900