You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复PowerShell脚本以实现USB串口的可靠读写?

修复PowerShell串口AT命令响应读取问题

核心问题排查与修复步骤

1. 严格匹配串口参数

Putty能正常通信,说明设备参数是确定的,必须让脚本和Putty使用完全一致的配置:

  • 波特率(常见9600/115200)、数据位(通常8)、停止位(通常1)、奇偶校验(无)、流控(通常无,或硬件流控)
  • 示例参数设置:
$port = New-Object System.IO.Ports.SerialPort("COM9", 115200, "None", 8, "One")
$port.Handshake = "None"
$port.ReadTimeout = 5000  # 设置读取超时,避免无限等待
$port.WriteTimeout = 2000

2. 确保AT命令发送格式正确

AT命令必须以\r\n作为结束符,设备才会识别并响应:

$port.Open()
$port.WriteLine("ATI`r`n")  # 注意用`r`n而非仅`n

3. 改进响应读取逻辑

串口响应是分批次返回的,不能单次读取,要循环读取直到超时或收到结束标记(如OK/ERROR):

$response = ""
$startTime = Get-Date
while ((Get-Date) - $startTime -lt [TimeSpan]::FromSeconds(5)) {
    if ($port.BytesToRead -gt 0) {
        $response += $port.ReadExisting()
        # 检查是否收到结束标记,提前退出循环
        if ($response -match "(OK|ERROR)") {
            break
        }
    }
    Start-Sleep -Milliseconds 100  # 短暂等待,避免CPU占用过高
}
Write-Host "完整响应:`n$response"
$port.Close()

4. 避免用独立pwsh.exe进程启动

直接在当前PowerShell会话中使用.NET SerialPort类,比跨进程通信更稳定,减少输入输出重定向带来的问题。如果必须用独立进程,要确保正确重定向标准输入输出,并同步读取:

# 独立进程方式示例(不推荐,仅作兼容)
$scriptContent = @'
$port = New-Object System.IO.Ports.SerialPort("COM9", 115200, "None", 8, "One")
$port.ReadTimeout = 5000
$port.Open()
$port.WriteLine("ATI`r`n")
$response = ""
while ($port.BytesToRead -gt 0) {
    $response += $port.ReadExisting()
    Start-Sleep -Milliseconds 50
}
$port.Close()
Write-Output $response
'@
$response = pwsh -Command $scriptContent
Write-Host "独立进程返回响应:`n$response"

5. 调试技巧

  • 开启串口日志:可以在脚本中把读取到的每一段数据都输出,排查是否有部分响应被遗漏
  • 对比Putty的串口参数:在Putty的Session->Serial里确认所有参数,完全复刻到脚本中

内容的提问来源于stack exchange,提问作者not2qubit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:00:09