开发者

How to send a reply message to sender machine via serial port using c#

I am using the below code to receive the message via serial port which is working fine. Now i need to send back a acknowledgment message to the sender machine. How can send the message ?

       private void MonitorSP_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            System.IO.Ports.SerialPort SP = (System.IO.Ports.SerialPort)sender;

            //Get the ports available in system
            string[] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
            string strAvlPortNames = "";
            foreach (string s in theSerialPortNames)
            {
                strAvlPortNames += s.ToString() + ", ";
            }

            //Read an contruct the message
            Thread.Sleep(1000);
            string msg = SP.ReadExisting();
            string ConstructedMsg = "Port's Found : " + strAvlPortNames + "\n" + "Port Used : " + SP.PortName + "\n" + "Message Received : " + msg;

            if (InvokeRequired)
            {
                richTextBox1.Invoke(new MethodInvoker(delegate { richTextBox1.Text = ConstructedMsg; }));
                //Send acknowlegement to sender port
                SP.Write(SP.PortName);
                return;
           开发者_如何学JAVA }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.StackTrace.ToString());
        }
    }  


You are already calling SP.Write(), that ought to be close. Although you probably don't want to send the port name back, the sender has little use for that. It also shouldn't be in the InvokeRequired test. Which is always true btw, you might as well remove that.

You also really want to get rid of the Sleep() call. Use ReadLine() if the sender terminates its message with a line feed ("\n"). If you are contemplating this because you need the sender to stop sending until it gets the acknowledgment then the real problem is in you using Sleep and ReadExisting.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜