3

I am using the Python-Arduino-Prototyping-API - v2 module to communicate with my Osepp Uno (Arduino Clone). The API does have a close() function which should close the port. I would like to check the status of the port when I open the program. If the port is open I'd like to close it so that the rest of the program can access the port.

Here's my code so far:

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)
Mike C.
  • 1,761
  • 2
  • 22
  • 46
  • If the port is open by another process, you might be out of luck for trying to close it. If you're just worried about a previous instance of your program holding it open for some reason, the handle to the port goes away when your program ends, one way or the other. – Matt Sieker Feb 05 '16 at 23:55
  • That's exactly what I'm concerned about. After running the program, I have to unplug the USB cable then plug it back in to make the port available. – Mike C. Feb 06 '16 at 00:03

1 Answers1

2

I figured it out. I used pySerial to check to see if the port was open and if so, I closed it. This ensures the port is available for the rest of the program.

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)

I hope this helps someone else.

Mike C.
  • 1,761
  • 2
  • 22
  • 46