连接时串行端口冻结 [英] Serial Port Freezes When Connecting

查看:89
本文介绍了连接时串行端口冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是我有一个为CAN做事的程序,现在CAN消息通过串行端口发送到终端应用程序,但是有时在尝试检测Com端口时卡住了.

该应用程序的运行方式如下:首先检测Com端口(这是卡住的端口),然后进行实际的连接并处理数据.
为了解决该问题,我通常必须拔出USB到串行电缆,然后重新启动该应用程序,这并不理想,因为该软件即将上线.

可能导致麻烦的原因之一是CAN代码被传送到串行端口中(无法停止).是在短暂的时间内打开了串行端口,无法处理数据并且它只是冻结,我需要延迟一点还是丢弃数据?
所以这是代码:

So here''s the thing I have this program that does stuff for CAN, now the CAN messages are being sent to the end Application via the Serial Port, sometimes however it gets stuck when trying to detect the Com Port.

The application operates as follows, First Detect the Com Port( this is where it gets stuck ), then do the actual connection and the process the Data.
To solve the problem, I usually have to pull out the usb to serial cable then restart the App, this is not ideal as this software is going Live soon.

One of the reasons it could be going haywire is that the CAN codes are being blasted into the serial port (This cannot be Stopped). Is it for that brief moment that the serial port is open for, the data cannot be processed and it just freezes, do I need to delay a bit or discard data??
So here''s the code :

for (int COM_Attempt = 1; COM_Attempt <= 50; COM_Attempt++)
          {
              string str_COM_Attempt = Convert.ToString(COM_Attempt);

              SP.PortName = "COM" + str_COM_Attempt;
              SP.BaudRate = 9600;
              try
              {
                  SP.Open();
                  SP.Close();

                  //Add port to the list of available ones
                  PortList.Items.Add("COM" + str_COM_Attempt);

              }
              catch
              {

              }
          }
          //Display the first entry
          PortList.Text = PortList.Items[0].ToString();
         }

推荐答案


看看 SerialPort.GetPortNames [ ^ ]

它是一项静态功能,可为您提供计算机上的所有串行端口.

Hi
Take a look at SerialPort.GetPortNames[^]

It is a static function, that give you all serial ports on the computer.

// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();


// Add each port to the list.
foreach(string port in ports)
{
  PortList.Items.Add("COM" + port);
}


这篇关于连接时串行端口冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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