Question

The function I am trying to create finds the port of a modem in charge of AT commands. I am trying to make different instances of serial.Serial() to be local to different loops. I looked in the documentation I could find for info, but none of the ones I found mentioned this in any way (if it is somewhere and I missed it, please feel free to make me look stupid and link it). For example:

    OpenPorts = []
    j=[]
    for modem in PortList:          #This opens every Modem
            for port in modem:
                    try:
                            j=[]
                            print port
                            ser = serial.Serial(port, 9600, timeout=1)
                            ser.close()
                            ser.open()
                            j.append(port)
                    except serial.SerialException:
                            continue
            OpenPorts.append(j) 
            print OpenPorts
    del j
    del ser

That works. But when I try this:

 for port in OpenPorts:
            if port is not '':
                    ser = serial.Serial(port, 9600, timeout=1) 
                    ser.write('ati')
 del ser

I get 'TypeError: can only concatenate list (not "int") to list'

I need to keep them local to the loops because I am opening multiple ports from a set list of ports in use (collected from another file). I have to use multiple loops because I need to use time.sleep() before ser.read() will return anything. Is there any way of doing it in this way, or is it back to the drawing board?

Was it helpful?

Solution

instead of storing the port:

j.append(port)

Why don't you append the ser instance so you can later use like this:

j.append(ser)

for ser in OpenPorts:
       ser.write('ati')

and the later you can close them all with :

for ser in OpenPorts:
       ser.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top