I have to send ZANE:1:00004:XX_X.X_XXXX_000XX:\\r\\n
via serial communication with python.
here is my code:
import serial
ser = serial.Seria
I believe the earlier answers didn't understand that you are using the same port for writing and reading.
I'm having the same problem and solved it using a sleep function. Basically:
import serial
from time import sleep
ser = serial.Serial('/dev/cu.usbserial-A901HOQC', timeout=1)
ser.baudrate = 57600
msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
ser.write(msg)
sleep(0.5)
ser.readline()
So with that sleep you are giving time to the receiver (a machine?) to send the reply. Also note that you have to add a timeout if you want to use readline.
In order to read you need to open a listening port(with a timeout) first, for example:
ser = serial.Serial('/dev/cu.usbserial-A901HOQC', 19200, timeout=5)
x = ser.read() # read one byte
s = ser.read(10) # read up to ten bytes (timeout)
line = ser.readline() # read a '\n' terminated line
ser.close()
See more details here.
Here two thinks are important.first one is timeout and second one is EOL charector.. if you are going to use time out in the receiver side then no need EOL from transmitter side. if you are going to use EOL charector in transmitter side(/n,/r) then no need to put time out in the receiver side. Ex: serialport=serial.serial(port,baud,timeout) if you are going to use time out incoming signal over serial port(Ex: hello how are you? nice to meet you man!!) Here new line cherector does not respond well.so you can leave it.
Ex: serialport=Serial.serial(port,baud) if you are not going to put time out in serial port then you should use end of line charector(/n,/r) in the transmitter Note : Second way is more efficient than first way
Your device is probably not terminating its response with a newline character. the .readline() method is expecting a newline terminated string. See here: http://pyserial.sourceforge.net/shortintro.html#readline for more info.
try setting a timeout on your serial connection
ser.timeout = 10
and replace the ser.readline() with ser.read(n) where n is the number of characters you wish to read. ser.read(100) will try to read 100 characters. If 100 characters don't arrive within 10 seconds, it will give up and return whatever it has received.