首页 > 解决方案 > 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

我应该怎么做才能以上述方式进行测试?先感谢您!- 拉维

标签: pythonpython-2.7spyderpyserial

解决方案


捕获输入的一种方法是使用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()

推荐阅读