9

I've read the documentation, but can't seem to find a straight answer on this. I have a list of all COM Ports in use by Modems connected to the computer. From this list, I try to open it, send it a command, and if it says anything back, add it to another list. I'm not entirely sure I'm using pyserial's read and write functions properly.

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            print ser.read(64)
            if ser.read(64) is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

I'm not getting anything out of ser.read(). I'm always getting blank strings.

RageCage
  • 722
  • 2
  • 6
  • 19
  • 2
    Have you tried running it? Are you getting an error message? Unexpected output? Or...? – lurker Oct 02 '13 at 17:50
  • What exactly is the issue? – That1Guy Oct 02 '13 at 17:52
  • Sorry, I forgot to write that down. I'm always getting blank strings out of ser.read(). I have it printing to see what it's returning. – RageCage Oct 02 '13 at 17:53
  • 1
    Why are you closing ser immediately after initializing it? That seems like it could be troublesome. – Chaosphere2112 Oct 02 '13 at 17:56
  • Couple of other issues springing out to me: `ser.read(64)` should be `ser.read(size=64)`, and you should assign it to a variable (`read_val = ser.read(size=64)`, followed by `print read_val` and then the if statement) because right now, you're performing two separate reads. – Chaosphere2112 Oct 02 '13 at 17:59
  • I was told to do that in case the port was already opened somewhere else. The function that this is a part of doesn't run without closing the port first, anyway. – RageCage Oct 02 '13 at 17:59
  • No problem :) glad to be of assistance. – Chaosphere2112 Oct 02 '13 at 18:06
  • I've posted the answer below, if you could accept it, that'd be great. – Chaosphere2112 Oct 02 '13 at 18:13

2 Answers2

12

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
PHMADEIRA
  • 129
  • 1
  • 4
10

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1
Chaosphere2112
  • 664
  • 7
  • 19