Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is working perfectly fine except I don't believe it is optimal and is going work reliably for fast response or handle significan delays.

Is there a better way of doing this? I would like it to just only wait for the arrival of the first 8 byte data on the buffer and read and continue on to the next task?
C++
Sleep (2000);                           //delay
serialPort1->;DiscardInBuffer();        //clear serial port in buffer
serialPort1->;DiscardOutBuffer();       //clear serial port out buffer

auto Power = gcnew array<System::Byte> {0x52, 0x0C, 0x01, 0x00, 0x00};
serialPort1->Write(Power, 0, Power->Length);


Sleep(500);
auto Power1 = gcnew array<System::Byte> {0x00, 0x00, 0x00, 0x00, 0x00};
serialPort1->Read(Power1, 0, Power1->;Length);

String^ str2 = String::Format("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2}", Power1[0], Power1[1], Power1[2], Power1[3], Power1[4]);

String^ str3 = String::Format("{2:N0}", Power1[0], Power1[1]);

richTextBox1-&gt;Text += "Power Level     ->   ";
richTextBox1-&gt;Text += str3 + "Watts" "\r\n";
Posted
Updated 7-Aug-14 9:33am
v2
Comments
Philippe Mori 7-Aug-14 20:32pm    
What is the purpose of the initial delay (2000 ms)?
Philippe Mori 7-Aug-14 20:36pm    
The easy way to do background processing is touse a background worker. For receiving, you also dont really need a wait but an appropriate timeout.
Member 10790434 8-Aug-14 15:19pm    
Philippe,
There isn't a need for the initial timeout but on the subsequent steps it does need it the way it is written now. How and where in code to put timeouts? Thanks.

A better way is to user overlapped communication, because sleep blocks the thread.

In this articel: Serial Communication in Windows is it well explained.

It makes also sense to create a write and a read thread for the port.

An article with background information but in C#.
 
Share this answer
 
You should get rid of all the Sleep calls and work asynchronously with the serial port: write your data and then and then handle the DataReceived event, gently provided by the SerialPort class (see SerialPort::DataReceived Event[^]).
 
Share this answer
 
Comments
Member 10790434 7-Aug-14 16:28pm    
CPallini/KarstenK, thank you.

I am using a single button click to write to and read from the serial port 8 data arrays sequentially in the same format as above for the remaining 7. The issue is if I remove the delays, I get bad data because there is not enough time for the arriving response.

DataReceivedHandler is definitely the way to go but I am not sure how I can get button_click and DataReceivedHandler to work together or if that is even possible?

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