0

I am using pyserial to read data off a serial port and sometimes the data I received behaves unexpectedly

Here is the important code

def getResponse():
    while ('\r' != rbuf[-1]):
        rbuf += s.read(s.inWaiting())
        print("b " + binascii.hexlify(rbuf))

    rbuf = rbuf.split('\r')
    rbuf = rbuf[:-1]
    print rbuf
    for char in rbuf:
        if(char == AFTER):
            print('a')
        elif(char == 'W'):
            print("Writing to the file")
        elif(char != ''):
            print char
            return char
    getResponse()

I understand that this isn't the best way to write the code, but somehting very stange happens.

When I receive the sequence ['a', 'A'] the value returned ends up being NONE.(which i check with a print statement elsewhere in the code

This does not happen when I receive ['W','a','A'] or when I recive ['A']

I figuired out a work around but I am really curious about this!!

Thanks

Ben

Treesrule14
  • 711
  • 7
  • 14
  • Due to indentation, you only appear to `return` in the case `elif(char != ''):` – jonrsharpe Nov 05 '14 at 16:17
  • I do only return in that case. (Hence the recursive call later if it doesn't work out) – Treesrule14 Nov 05 '14 at 16:18
  • So if that `elif` never executes, then you reach the end of the function without returning anything, so `None` gets returned implicitly. That's not too surprising to me. – Kevin Nov 05 '14 at 16:18
  • In all other cases, then, you get `None`. Could you provide a complete [minimal example](http://stackoverflow.com/help/mcve) and explain the issue more clearly? – jonrsharpe Nov 05 '14 at 16:19
  • Sorry this is in the function GetResponse(). I tried making a "minimal example" but this was the best I got. – Treesrule14 Nov 05 '14 at 16:19

1 Answers1

2

I don't entirely understand your code, but I strongly suspect that you want to return the result of the recursive getResponse call at the end of your function. If so, you need to explicitly return. Just calling the function won't do it for you.

getResponse()

Becomes

return getResponse()
Kevin
  • 74,910
  • 12
  • 133
  • 166