上段代码退出后报错 raise SerialException("ReadFile failed ({!r})".format(ctypes.WinError())) serial.serialutil.SerialException: ReadFile failed (OSError(9, '句柄无效。', None, 6)),需要怎么更改
时间: 2024-02-11 22:07:12 浏览: 271
这个错误通常是由于串口被其他程序或线程占用而导致的。你可以尝试以下几种方法:
1. 在关闭串口之前,先调用serial_thread.stop()方法停止串口线程的运行,然后再关闭串口。代码如下:
```
def closeEvent(self, event):
# 停止串口线程的运行
self.serial_thread.stop()
# 关闭串口
self.serial_thread.serial.close()
# 调用父类的closeEvent()方法
super().closeEvent(event)
```
在这个代码中,我们在关闭窗口之前,先调用了`self.serial_thread.stop()`方法停止串口线程的运行,然后再关闭串口,最后调用了父类的`closeEvent()`方法。
2. 在串口读取数据的过程中,加上异常处理语句,防止出现异常导致程序崩溃。代码如下:
```
def run(self):
while not self.stopped:
try:
data = self.serial.read(1)
except:
continue
if data:
self.data_received.emit(data)
```
在这个代码中,我们使用了try-except语句捕获异常,如果出现异常则直接跳过,继续下一次循环。
如果以上方法都无法解决问题,可以尝试重启计算机,或者尝试更换其他串口进行测试。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)