首页 > 解决方案 > COM 端口通讯问题,Text To ASCII

问题描述

我正在制作一个简单的程序,将信息从 PC 发送到 COM 端口。到目前为止,我已经在 PC 和 COM 端口之间建立了连接,我可以发送信息并查看端口接收到的内容,但是我有两个问题,第一个是当我将信息发送到实际的 COM 端口(COM 端口到 USB 电缆制成回显信号)我第一次收到所有信息。然后它变得随机,有时又是我写的所有内容,有时只是第一个字符。有时什么也没有。我的假设是发生这种情况是因为我没有设置任何超时或任何东西。对此有帮助会很好。

但我遇到的真正问题是我希望从文本框发送的所有信息都以 ASCII 码发送,因为我正在制作与 PLC 通信的程序。

这是代码:

   public Form1()
    {
        InitializeComponent();
    }
    //BTN new serial port creation - port taken from comport text box
    private void button1_Click(object sender, EventArgs e)
    {
        System.IO.Ports.SerialPort sport = new System.IO.Ports.SerialPort(comport.Text, 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);

        //opening the com port and sending the information from textbox1
        try
        {
                sport.Open();
            sport.Write(textBox1.Text);

        }
        //if there is an error - show error message 
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        //Adding timestamp to received info
        DateTime dt = DateTime.Now;
        String dtn = dt.ToShortTimeString();
        //reading the information form the com port
        textBox2.AppendText("[" + dtn + "] " + "Recieved: " + sport.ReadExisting() + "\n");
        //closing the port
        sport.Close();
    }

标签: c#serial-portascii

解决方案


问题是,您每次单击按钮时都在阅读,并且可能没有收到所有内容。您应该使用SerialPort类的DataReceived事件来接收您的数据。每次通过您的 COM 端口接收到数据时都会触发该事件,因此您可以按下按钮写入端口,然后当数据进入时,您应该会看到事件与您的数据一起触发。

微软在这里有一个很好的定义和例子。

该事件在一个单独的线程上,因此要将其写入文本框,您可能必须调用它才能在您的 gui 上显示它。请参见下面的示例代码:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string Data = serialPort1.ReadExisting();

    this.Invoke((MethodInvoker)delegate
    {
        textBox2.AppendText(Data);
    });
}

推荐阅读