我正在使用Python-Arduino-Prototyping-API-v2模块与我的Osepp Uno(Arduino Clone)进行通信。 API确实有一个close()函数,它应该关闭端口。我想在打开程序时检查端口的状态。如果端口是打开的,我想关闭它,以便程序的其余部分可以访问端口。
到目前为止,这是我的代码:
from arduino import Arduino
import time
import serial.tools.list_ports
#Find USB Port
def find_port(): #Finds which port the arduino is plugged into
ports = list(serial.tools.list_ports.comports())
for p in ports:
if '0403' in p[2]:
print p
return p[0]
usbport = find_port()
b = Arduino(usbport) #adds port
pin = 0
b.output([])
while (True):
val = b.analogRead(pin)
print val
print usbport
time.sleep(0.05)
答案 0 :(得分:1)
我明白了。我使用pySerial检查端口是否打开,如果是,我关闭它。这可确保端口可用于程序的其余部分。
from arduino import Arduino
import time
import serial.tools.list_ports
import serial
#Find USB Port
def find_port(): #Finds which port the arduino is plugged into
ports = list(serial.tools.list_ports.comports())
for p in ports:
if '0403' in p[2]:
print p
return p[0]
usbport = find_port() #Calls function to get Arduinos USB port
def closeport(): #Closes port if currently open
ser = serial.Serial(usbport)
if ser.isOpen() == True:
ser.close()
closeport() #make sure port is available
b = Arduino(usbport) #opens Arduino with correct port
pin = 0 #Assigns analog out, pin 0
b.output([])
while (True):
val = b.analogRead(pin)
print val
print usbport
time.sleep(0.05)
我希望这有助于其他人。