how to completely send a string through serial port

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ChongHan
    New Member
    • May 2013
    • 1

    how to completely send a string through serial port

    Hi

    I am doing a messaging application using Visual C++ window form application.

    Sometimes I can't receive a whole message from the sender. If i type short sentence like "123456", it can be shown properly. But, if i type a quite long sentence like "12345678912345 6789", it can't shown a correct message, can't show exactly the whole message.

    here is my code:

    Code:
    //transmission:
    String^ message;
    String^ message1;
    String^ name = this->serialPort1->PortName;
    // grab text and store in send buffer
    message = this->richTextBox2->Text;
    // write to serial
    if(this->serialPort1->IsOpen)
    this->serialPort1->WriteLine(message);
    this->serialPort1->DiscardOutBuffer();
    this -> serialPort1 -> DiscardInBuffer();
    }
    
    //Receving code:
    demessage = " ";
    ciphertext = " ";
    try
    {
    ciphertext = this->serialPort1->ReadExisting();
    this -> Invoke (gcnew System::EventHandler(this, &Form1::DisplayText));
    }
    catch(TimeoutException^)
    {
    MessageBox::Show("Timeout Exception");
    }
    private: System::Void DisplayText (System::Object^ s, System::EventArgs^ e)
    {
    this -> richTextBox1 -> Text = String::Empty;
    this->richTextBox1->AppendText(ciphertext);
    }
    Last edited by Rabbit; May 9 '13, 03:50 PM. Reason: Please use code tags when posting code.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    A serial port provides a byte stream, it is not message based. There is no such thing as a whole sentence as far as a serial port is concerned.

    That means you need to be able to tell from the data transmitted where the end of the sentence is, for example you transmit a sentinel character (say a full stop) which you can look for when receiving to indicate the end of data.

    Then you read the serial port in a loop and you keep reading it until you have received the end of data marker, and then you output the data (sentence) you have received.


    Also I don't know how .NET handles the serial port but in your writer it seems a little strange to discard the output buffer immediately after having written data to the port. How do you know that all the data was actually sent? It takes time to send data on a serial port, a lot more time than it takes the processor to process commands. I would have thought a command to flush the output buffer (if one exists) would be a better thing to call.

    Comment

    Working...