I am trying to communicate with my module by using a Python file. I create line-break point to be sure that I will have an interruption while writing in the module.
But, I don't have any result for reading from the port communication. I need to display all data in my cmd.exe and that already diplayed on COM4 by using my python file
import serial
ser = serial.Serial(
port='COM4',\
baudrate= 230400,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0) # open serial port
print(ser.name) # check which port was really used
ser.write(b'hello') # write a string
str=ser.readline()
print str
ser.close() # close ports
That means that these two lines:
str=ser.readline()
print str
don't give me any results.
What's most likely happening is that ser.readline()
is waiting for a newline char (\n
) to be received on the serial port, but isn't getting it so it hangs. If your serial port is set to echo what you're sending it, you likely need to include the newline char with the data you send it, i.e.
ser.write(b'Hello\n')
or, if your serial device is expecting Windows style newlines:
ser.write(b'Hello\r\n')
If you're stilll not getting any response, you can try debugging after your ser.write
statement with
while True:
print(ser.read(1).decode())
in order to display every byte as it comes back Note: only use the above for debugging, it will hang until the device is closed outside your script.
If you see nothing, then there's probably something more fundamental going on, like the serial port setup. I notice that your baud rate is not a standard baud rate, are you sure that's right?
Side note: there's no need for the backslashes after each argument in your serial.Serial
declaration, the fact that the text is within enclosed parentheses makes the code valid. Also, you're supplying the default arguments for most of the parameters, so there's no need to include them at all.
Another aside: working with I/O devices that block on read
s can be tricky, and it might be useful setting up a reader thread that pushes data received into a queue.Queue
object like what's described here. Or if you're feeling adventerous, try using the asyncio
module.