Reputation: 1223
I wrote a basic program using pyserial to send and receive data.
import serial
ser = serial.Serial()
ser.port='COM9'
ser.open()
ser.write(b'hello\n')
data = ser.read()
print data
However the program is not printing any output and not terminating in the command prompt.
Upvotes: 2
Views: 28740
Reputation: 69
All data coming to the serial port in linux is stored in the files. Therefore, it is necessary to check the file with a certain frequency. You can use a for-loop to do this. Your mistake is that you send data and try to get it on the same port. And this is not possible. You need a physical connection between 1 and 2 serial ports. Here is an example: So your 1 Serial port TX must be connected with 2 Serial port RX and vice versa 2 SP RX with 1 SP TX
There is some python3 code to listen on serial port and write data on another serial port.
write.py:
import serial
#init serial port and bound
# bound rate on two ports must be the same
ser = serial.Serial('/dev/ttyS2', 9600)
print(ser.portstr)
#send data via serial port
ser.write("012345688902341")
ser.close()
listen.py:
import serial
serBarCode = serial.Serial('/dev/ttyS1', 9600, timeout=1)
while True:
#read data from serial port
serBarCode = serBarCode.readline()
#if there is smth do smth
if len(serBarCode) >= 1:
print(dataBarCode.decode("utf-8"))
Firstly execute listen.py and after that parralely execute write.py
Upvotes: 3
Reputation: 162
A serial connection has one Tx line (send) and one Rx line (receive). These are not connected. So if you send out something on Tx with write(...) you will not see that message on the Rx line with read().
If you want a loop, you need two serial object on two serial COMs and connect the two serial ports. Then you can send from one object and read from the other.
Upvotes: 0