COM 端口通信问题,文本到 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();
}

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

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

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

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string Data = serialPort1.ReadExisting();
this.Invoke((MethodInvoker)delegate
{
textBox2.AppendText(Data);
});
}

最新更新