Reputation: 135
I am trying to make a program which run serial communication with another program in python. In my program, I want to wait a specific incoming data. So far, I have successfully done it with this command :
while ser.read(length)!= incoming_data:
pass
But the incoming_data has various possibility. I want to check what data is coming and do a specific task for each incoming data. In tera term macro I can use this code:
wait data1 data2
if result = 1 then .....
if result = 2 then ....
How can I do the same thing in python serial? because each data has different length. Thanks in advance.
Upvotes: 0
Views: 3596
Reputation: 19554
You could buffer the incoming data and then check for matches. Something like
buf = ''
while 1:
buf += ser.read(1)
if buf == data1:
# do stuff
buf = ''
elif buf == data2:
# do something else
buf = ''
Upvotes: 0
Reputation: 11849
In my experience you need a terminating character of some kind to indicate the end of the message. Typically the newline character is used (\n
). pyserial has a method readline()
which will read until it reaches a newline character and then return that data.
Upvotes: 1