python函数实现对串口1~4进行不同波9600/19200/115200特率的连接尝试;若连接成功,则发送"*IDN?"获取仪器类型;判定设备类型是否在读dev_config.xlsx的设备列表中;
时间: 2024-05-09 08:19:43 浏览: 12
以下是一个可能的实现方案:
```python
import serial
import pandas as pd
# 读取设备列表
dev_df = pd.read_excel('dev_config.xlsx')
dev_list = dev_df['device_type'].tolist()
# 尝试连接串口并发送命令
def try_serial_connect(port, baudrate):
ser = serial.Serial(port=port, baudrate=baudrate, timeout=1)
ser.write(b'*IDN?\n')
resp = ser.readline().decode().strip()
ser.close()
return resp
# 尝试连接串口1~4并判断设备类型
for i in range(1, 5):
for baudrate in [9600, 19200, 115200]:
port = f'COM{i}'
resp = try_serial_connect(port, baudrate)
if resp:
print(f'{port} @ {baudrate}: {resp}')
if resp in dev_list:
print(f'{resp} is in the device list')
else:
print(f'{resp} is not in the device list')
break
```
其中,`try_serial_connect()` 函数尝试连接指定的串口并发送 `*IDN?` 命令获取设备类型,最后关闭串口并返回设备类型字符串。在主程序中,我们使用两层循环分别尝试连接串口 1~4,以及三种不同波特率,如果连接成功则输出设备类型并判断是否在设备列表中。需要注意的是,如果设备类型在列表中出现多次,这个程序仅会判断第一次出现的位置。如果需要考虑所有出现位置,可以使用 `dev_df['device_type'].str.contains(resp)` 进行判断。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)
![](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)