python - Python pyserial
问题描述
我正在从 python 2.7 anaconda spyder 64 位触发一个名为 olfactometer 的设备。该嗅觉计中有八个电磁 TTL 阀。如果我想切换那个阀门的状态,我只需要编写下面提到的代码。
import serial
import time
port = serial.Serial("COM3", 19200, timeout=0.5)
#turn on port 2, sleep 2 seconds, turn off port 2
port.write(b"\nF2\r") # if opened then close port 2
time.sleep(2.0)
port.write(b"\nF2\r") # if closed then open port 2
#close the port
port.close()
我想知道,是否可以从 0 或 1 给端口 2 特定值?
例如
if 'e' in keypress:
# it must open the port 2
if 'i' in keypress:
# it must close the port 2
我应该怎么做才能以上述方式进行测试?先感谢您!- 拉维
解决方案
捕获输入的一种方法是使用raw_input
内置函数(input
在 Python3 中)。例如
port = serial.Serial("COM3", 19200, timeout=0.5)
prompt = 'Press "e" to open, "i" to close, and "q" to quit: '
keypress = raw_input(prompt)
while keypress != 'q':
if keypress == 'e':
port.write(b"\nF2\r") # if closed then open port 2
print('Opened')
elif keypress == 'i':
port.write(b"\nF2\r") # if opened then close port 2
print('Closed')
# prompt again
keypress = raw_input(prompt)
port.close()
推荐阅读
- pandas - 通过循环更改列名
- json - 有没有办法我们可以在门户中查看失败的 arm 模板部署的输出?
- flutter - 有什么方法可以在颤振中使用 gojs 图表吗?
- python-tesseract - python tesseract 不能在 Heroku 上工作,我 pip 它,它安装了,但不工作?
- html - 如何创建具有正确角半径的线?
- reactjs - 如何让 VSCode 不检查目录中的其他 .ts 文件是否存在变量冲突?
- wordpress - 有没有办法防止键盘弹出în wrpdress
- c# - 仅在创建操作期间实体框架的 C# 验证注释
- php - 通过composer在laravel上安装包时出错
- java - Graal SDK 在应用程序运行但在单元测试中失败时工作