使用c#从串口部分接收消息 [英] Receiving messages part by part from serial port using c#

查看:55
本文介绍了使用c#从串口部分接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码从使用 c# 的串口接收消息

I am using the below code to receive the messages from serial port using c#

    void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (comPort.IsOpen == true)
        {
            string msg = comPort.ReadExisting();
            MessageBox.Show(msg.Trim());
        }
    }

问题是,我正在逐部分获取消息.比如,如果你发送你好,你好吗"我正在逐字逐句地接受它.我想要一次.我该怎么办??

The problem is, i am getting the messages part by part. Like, if u send "Hello, How are you" I am receiving it word by word. I want that in a single stretch. How can i do ??

此外,是否可以检索应用程序发送和接收消息的端口名称?

Also, is it possible to retrieve the port name from which the application is sending and receiving messages ?

推荐答案

   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;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace.ToString());
            }
        }  

这篇关于使用c#从串口部分接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆