Search code examples
pythonpyserialuartmodem

Python Serial Read


Having trouble reading serial data from a USB modem and can't find anyone with the same issue.

Using the code below, I can write to the serial port successfully but when I read, the terminal just sits there accepting input but does nothing with it. I can type anything I like and enter carriage returns but they don't do anything. It's like I've created an infinite input loop but I don't see how that could have happened. Eventually I have to Crtl-c out of the program.

I've tried other approaches, such as reading a specified number of bytes or reading into a variable and looping through it but critically, a call to inWaiting() or in_waiting returns 0, so there's clearly nothing to read despite the write command being successfully accepted by the modem.

Anyone got any thoughts on where this infinite loop is coming from and why I'm not seeing my modem's responses?

import time
import serial

ser = serial.Serial("/dev/ttyUSB2", 115200)

time.sleep(1)
ser.write(b'\r\n' + b'at' + b'\r\n')

time.sleep(1)
print(ser.readline())

SOLVED: I think timeout made the difference (thanks to RaulG). I started seeing either b'\r\n' or in another case b'at\r\n' being returned and found that my response was being split over multiple lines and seems to include an echo.

With the following code I was able to see the full response.

Code:

import time
import serial

ser = serial.Serial(port="/dev/ttyUSB2", baudrate=115200, timeout=5)

time.sleep(0.5)
ser.write(b'at\r\n')

time.sleep(0.5)
print(ser.readline())
print(ser.readline())
print(ser.readline())

Output:

b'at\r\n'
b'\r\n'
b'OK\r\n'

Solution

  • First of all the ser.readline() command is the infinite loop. It waits until there is a \n Charakter in the input buffer. You can avoid the loop by specifying a timeout in the initialization of the serial.Serial Object like this (timeout in seconds)

    ser = serial.Serial('/dev/ttyUSB2',115200,timeout=2)
    

    Now to the part that there is nothing that you receive from the modem. This might have different reasons and cannot be properly answered by the informations you have provided. First there might be something wrong with your usb to serial adapter. Then you might have incorrectly wired something or your modem might have a problem electrically or with its software.