C++ 串行(COM)-在Windows上重新连接端口

C++ 串行(COM)-在Windows上重新连接端口,c++,windows,serial-port,C++,Windows,Serial Port,我正在写一个小软件,通过串口连接到Arduino或Teensy。我想让软件实现,如果USB串行断开连接,并自动重新连接时,再次插入 这在Linux下非常简单,但我甚至不确定在Windows下是否可行,因为我发现的所有终端程序都无法在COM端口断开连接后重新连接,而无需重新启动 我目前使用Qt5qSerialPoT实现,但是如果有人知道C++类能够正确地重新连接而不重新启动程序,我会在一秒钟内改变。 此外,如果有人知道一个串行终端程序,可以自动重新连接,我将非常感谢一个答案 编辑我使用的是64位W

我正在写一个小软件,通过串口连接到Arduino或Teensy。我想让软件实现,如果USB串行断开连接,并自动重新连接时,再次插入

这在Linux下非常简单,但我甚至不确定在Windows下是否可行,因为我发现的所有终端程序都无法在COM端口断开连接后重新连接,而无需重新启动

我目前使用Qt5qSerialPoT实现,但是如果有人知道C++类能够正确地重新连接而不重新启动程序,我会在一秒钟内改变。 此外,如果有人知道一个串行终端程序,可以自动重新连接,我将非常感谢一个答案


编辑我使用的是64位Win7,通常是32位程序。

关键是,当连接到串行端口的设备断开连接时,您将在读取行中接收null,因此如果为null,您将尝试重新连接。另外,您需要设置一个超时,否则readline将永远等待。 Python示例:

import serial
import threading
import time
class MainTHread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._data = ""
        self.ser = None
    def run(self):
        while(True):
            try:
                time.sleep(1)
                ser = serial.Serial('COM3',9600,timeout=2)

            except serial.SerialException as err:
                print("Connection failed")
                try:
                    ser.close()
                except UnboundLocalError:
                    print("No Serial")
                print(err)
                continue
            while True:
                try:
                    print("Trying to read")
                    data_json = ser.readline()
                    self._data =data_json.decode('UTF-8');
                    if(not self._data):
                        break
                    print("Main Thread " + self._data)
                except serial.SerialException as err:
                    print("Connection failed")
                    ser.close()
                    break
    def getData(self):
        return self._data
thread = MainTHread()
thread.start()
在Powershell上更轻松:

function triaComPort(){
$selection = [System.IO.Ports.SerialPort]::getportnames()

If($selection.Count -gt 0){
    $title = "Serial port selection"
    $message = "Which port would you like to use?"

    # Build the choices menu
    $choices = @()
    For($index = 0; $index -lt $selection.Count; $index++){
        $choices += New-Object System.Management.Automation.Host.ChoiceDescription $selection[$index]
    }

    $options = [System.Management.Automation.Host.ChoiceDescription[]]$choices
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

    $selection = $selection[$result]
}

return $selection
}

$port = triaComPort

if(!$port){"Must choose";return}

Write-Host $("Port:"+$comport)
$port= new-Object System.IO.Ports.SerialPort $port,57600,None,8,one

while($true){
    if(!$port.IsOpen){
        try{
            $port.Open()
            write-host "+" 
        }catch{
            write-host "-" -NoNewline
        }
    }
    if($port.BytesToRead -gt 0){
        Write-Host $port.ReadExisting()
    }
}
$port.Close()
此脚本打印-无法连接时+连接时,速度固定在57600,您可以更改它


希望有帮助。

如果重新连接,为什么需要重新启动程序?我使用了类似的东西,但使用python,我使用了一个线程通过串行端口获取数据。很好,你有python的示例代码吗?这在Windows上确实有效,对吗?我不知道为什么我必须重新启动,但Putty、hTerm、hyperterm和其他3个我尝试过的工具也必须重新启动。我把它作为一个答案发布,因为它有太多的字符供评论。你与5美元硬件相处的典型USB设备驱动程序不适合这个任务,你必须花真正的钱。断开连接之前,请始终使用“安全删除硬件”托盘图标。为什么这是一个驱动程序问题?在我断开设备后驱动程序没有卸载吗?或者它一直开着,因为它没有关好。。。下面的python示例证明了这是可以做到的。谢谢你的代码,但对我来说不起作用。当我断开USB/串行端口并再次插入时,它会在同一COM端口下再次出现,但python脚本返回“连接失败”,并且
err
包含“系统找不到指定的文件”。这与我经常遇到的错误相同。系统是Windows 7 64位,我安装了32位python和pyserial顺便说一句。尝试增加超时在调用
serial.serial…
后立即发生错误。我将超时时间增加到10,但没有成功。这很奇怪。类似于当你重新连接时,你的设备不可用;我没认出。将此块
除了serial.SerialException作为err:print(“连接失败”)break
替换为
除了serial.SerialException作为err:print(“连接失败”)ser.close()break
,这正好解决了问题。您必须确保在第一次尝试时,即在设备断开连接的情况下启动时,不要执行
ser.close