开发者

Using SerialPort class to read response from connected device

开发者 https://www.devze.com 2023-01-15 08:44 出处:网络
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

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 rec开发者_Python百科eiving 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;
            }
        }


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


By default, the device (a modem I guess) is configured to echo all communication back. There are AT commands to turn echo on and off. Also, several hardware signalling approaches exist to control the flow of data. Have a look here for a basic overview.

It's quite a while (> 10 years actually) since I was doing modem communications, so I'm sorry in case my answer isn't 100% precise.

0

精彩评论

暂无评论...
验证码 换一张
取 消