anna carolina
anna carolina

Reputation: 209

Messagebox working in debug mode but not in normal run

I am making a software for GSM Modem. It works on serial communication using AT commands. We give AT commands to it and it respond via serial communication. I am giving it a command to check balance in a SIM AT+CUSD=1,"*141#". Its response is like this:

+CUSD: 0, "Your balance is ... xxxxxxx "

Now I want to display this on a messagebox. This is the small code I am using:

String data = serialPort1.ReadExisting();  //to receive serial data and store it in data strig
logsTextBox.AppendText(data);  // display it in text box
logsTextBox.AppendText("\n");

if (data.Contains("+CUSD:"))
{
  MessageBox.Show(data);
}

Now when I put breakpoint and debug the code, it works properly and show complete data in message box but when I run it normally it shows just few characters in message box. Like this:

enter image description here

Instead it should be like this:

enter image description here

The problem what I have found is when debug all the data content which is shown in 2nd image gets save in data variable so it is displayed completely in message box. But when in normal run, the complete data is not received in string data so thats why it shows less data as shown in first image. How to solve this issue. What could be the reason. Please help.

Upvotes: 1

Views: 230

Answers (2)

umeshkumar sohaliya
umeshkumar sohaliya

Reputation: 267

This is a typical behavior for a serial port. They are very slower. When the DataReceived event fires, you'd typically only get one or two characters. Notably is that it works well when you debug because single-stepping through the code gives the lots of time to serial port to receive additional characters. But it will go Kaboom as soon as you run without a debugger because the string isn't long enough.

You'll need to modify the code by appending the string you receive to a string variable at class scope. Only parse the string after you've received all the characters you expected. You'll need some way to know that you've received the full response. Most typically serial devices will terminate the string with a special character. Often a line-feed.

If that's the case then you can make it easy by setting the SerialPort.NewLine property to that terminator and calling ReadLine() instead of ReadExisting().

Upvotes: 1

Graphic Equaliser
Graphic Equaliser

Reputation: 197

You should call ReadExisting until empty string is returned, concatenating the results to data on each call. Perhaps debug mode has a larger read buffer for the serial port than normal mode.

Upvotes: 0

Related Questions