Search code examples
c#serial-portcom-port

Using SerialPort class to read response from connected device


I'm using C#'s SerialPort class to try and send a AT command to a device and get a response back. I've verified it works correctly in HyperTerminal, if I send a command of AT it responds back with OK. However, in my console app, if I send AT, it replies back with an echo AT. The code is below, any insight into what I'm doing wrong in my receiving code would be greatly appreciated:

ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived);

public void Open()
        {
            Console.WriteLine();
            //close port if already open.
            if (ComPort.IsOpen)
            {
                ComPort.Close();
            }
            //setup port.
            ComPort.PortName = ConfigurationManager.AppSettings["PortName"].ToString();
            ComPort.BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]);
            ComPort.Parity = Parity.None;
            ComPort.StopBits = StopBits.One;
            ComPort.DataBits = 8;
            ComPort.DtrEnable = true;
            ComPort.RtsEnable = true;
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["HWFlowControlEnabled"]))
            {
                ComPort.Handshake = Handshake.RequestToSend;
            }
            //open port.
            Console.WriteLine("Opening port " + ComPort.PortName + "...");
            ComPort.Open();
            Console.WriteLine("Opened port " + ComPort.PortName);
        }

void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string message = ComPort.ReadExisting();
            Console.WriteLine("RECEIVED: " + message);
            if (message.IndexOf("OK") > -1)
            {
                ReceivedOK = true;
            }
        }

Solution

  • I think the default is to echo your commands back to you, then the OK. Send an ATE0 first to turn off echo:

    http://tigger.cc.uic.edu/depts/accc/network/dialin/modem_codes.html