Aaron
Aaron

Reputation: 37

Serial port read result contains response but also the command I give, how to solve this?

I am writing a GUI for Modem communication tool, able to receive AT command and also return the result from modem after execution in modem. I use serial port datareceived event to handle the received data but it contains not only the response from the modem but also the AT command I give. Now I think it is because:

1) send at command from my GUI

2) Modem receive it, then trigger datareceived events

3) Modem runs the command, the reply also trigger datareceived events.

4) the received data then contains both my given command and also the reply

For example:

Input: AT+COPS=0

Output:AT+COPS=0OK (OK is modem response)

Input: AT

Output:ATOK (OK is modem response)

I could not find a solution in MSDN. Are there two different buffers in Modem? How to solve this?

Here is my code:

void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{

    if (e.EventType != SerialData.Chars)
    {
        return;
    }
    try
    {
        System.Threading.Thread.Sleep(1000);
        string indata = atPort.ReadExisting();
        string status = timeStamp.ToShortDateString() + " " + timeStamp.ToUniversalTime() + "   " + "Read from Modem: " + indata;
        this.Invoke(new MethodInvoker(delegate () { this.listBox_CommandOutput.Items.Add(status); }));
    }
    catch (Exception ex)
    {

    }
}


private void executeCommandLine()
{
    if (this.textBox_CommandLine.Text != "")
    {
        try
        {
            atPort.DiscardInBuffer();
            atPort.DiscardOutBuffer();
            this.atPort.Write(this.textBox_CommandLine.Text.ToString()+"\\r");
            this.listBox_CommandOutput.Items.Add(timeStamp.ToShortDateString() + " " + timeStamp.ToUniversalTime() + "   " + "Write to Modem: " + this.textBox_CommandLine.Text.ToString());

        }
        catch (Exception exc)
        {
            this.listBox_CommandOutput.Items.Add(exc.ToString());
        }
    }
    else MessageBox.Show("Command can't be void.", "COM talk", MessageBoxButtons.OK);

}

Upvotes: 1

Views: 940

Answers (1)

aghidini
aghidini

Reputation: 3010

The problem is not in your code. Some modem by default use the echo mode by default: they echo every character sent to them to the sender (so you can use them like a terminal).

You can disable the echo mode using the AT command:

ATE0

Upvotes: 3

Related Questions