I'm writing a python script that connects to a USB serial device. Whenever a command is sent and executed, the PIC returns with a hashtag. Ie. "Command executed successfully. \\n# "
I'd like my python script to wait for the hashtag before outputting the data. How can I do this? Here's what I have. It doesn't seem to actually print the text received from the PIC. Any help is appreciated
if port.isOpen():
try:
for x in range(0,100):
time.sleep(0.05)
port.write("command 1" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
time.sleep(0.05)
port.write("command 2" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
time.sleep(0.05)
port.write("command 3" + "\r\n")
numLines = 0
// wait for "#" to print output
while True:
response = port.readline()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
except Exception, e1:
print("An error occured: " + str(e1))
port.close()
port.readline()
will read the serial port till it receives a \\n
. So, the response will contain the string "Command executed successfully. \\n". Since there is no "#" in this string, again the code will encounter the port.readline()
statement. This time it will read "#" but since there is no "\\n", the code will be stuck there resulting in an infinite loop.
Pyserial provides a method called read():
read(size=1)
Parameters: size – Number of bytes to read. Returns: Bytes read from the port. Return type: bytes Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.
read() provides a parameter size (with default =1) which specifies the number of bytes to be read. So, you can specify the number of bytes in the string sent by the PIC as a parameter. You can also use the following alternative:
// wait for "#" to print output
while True:
response += port.read()
if "#" in response:
print(response)
numLines = numLines + 1
if(numLines >= 1):
break
If you send some white space to the device, as if it were a terminal command, it will prod it into a response with your "#" in it. I have been successfully using that method. Specifically I send a single space " " plus the terminal line ending (ie "\\n" or "\\r\\n" depending on the device).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.