python pyserial writing more than once to serial port - python

I am writing and reading from the same serial port. Here is what problem is:
When I write to serial port one after another, like in the code below:
import serial
import array
rec = serial.Serial()
trans = serial.Serial()
rec.port = "/dev/ttyUSB0"
rec.baudrate = 9600
rec.timeout = 0.5
rec.open()
trans.port = "/dev/ttyUSB0"
trans.baudrate = 9600
trans.timeout = 0.5
trans.open()
if trans.isOpen():
trans.write("\xFE\x1D\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xE2")
trans.write("\xFE\x1D\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xE3")
while rec.isOpen():
response = rec.readline()
etc. etc. etc
As long as while loop turns, I keep reading only the first sent string. Also I tried to send data just after the while loop: (I did not delete the if statement)
while rec.isOpen():
trans.write("\x00\x00")
response = rec.readline()
What I read from the serial port is still:
"\xFE\x1D\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xE2"
I cannot send any other data other than the first one. Why is it happening? What should I do?
note: Also in the while loop I tried to read twice:
response = rec.readline()
response = rec.readline()
This time, when I print the array that I read, it prints [] which means I cannot read anything.
Regards
EDIT: Now I used two different usb ports ttyUSB0 and ttyUSB1 to check if my problem is related to that situation. But seems like nothing is wrong with writing and reading from the same port.

The issue can be port misconfiguration. You have to set proper values
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=???,
stopbits=???,
bytesize=???)

I did not see newlines, so you should try with rec.read(bytes) or finish lines with \0d\0a or something.
See http://pyserial.sourceforge.net/shortintro.html#readline

Related

Unable to send/receive data via HC-12/UART in Python

I've written some code to communicate between two Raspberry Pi's, using identical HC-12 433Mhz transceivers. I was able to successfully echo between the two Pi's using a direct serial connection and echo/cat, however am unable to replicate this using HC-12s, which theoretically work by a similar principal. I'm using the port ttyAMA0 on both for this example, but ttyS0 is also available and have tried every combination of these ports.
The following code is common to both the sending and receiving, just writing once for sake of brevity:
import serial
import time
ser = serial.Serial(
port = "/dev/ttyAMA0",
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS
)
print("Serial status: " + str(ser.isOpen()))
This is the sending program:
while True:
print("Sending...")
ser.write("hello\n".encode())
time.sleep(1)
And the receiving program:
while True:
print("Receiving...")
data = ser.readlines()
print(data.decode())
The sending program simply loops as expected, but the receiver prints "Receiving...", and then nothing.
When I keyboard interrupt the receiving program at that point, it says it is currently up to data = ser.readlines().
Any help would be much appreciated - I've spent the better part of the last week trawling and exhausting forums and READMEs to no avail, and this is literally my last option. Am close to insanity on this one!
The pyserial readlines() function relies on the timeout parameter to know when end-of-file is reached - this is warned about in the doco. So with no timeout, the end never occurs, so it keeps buffering all lines read forever.
So you can just add a timeout to the serial port open, and your existing code will begin to work.
ser = serial.Serial(
port = "/dev/ttyAMA0",
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 2 # seconds # <-- HERE
)
A better approach might be to use readline() (note singular, no 's'), for each line in turn:
print( "Receiving..." )
while True:
try:
data = ser.readline()
print( data.decode() )
# TODO - something with data
except:
print( "Error reading from port" )
break
As that will allow the code to act on the input line-by-line.
Use Serial.read_until method. The default termination character is \n.
For example,
data = ser.read_until()
print(data)

How to read and write from a COM Port using PySerial?

I have Python 3.6.1 and PySerial Installed. I am trying the
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
Code:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
I see from the PySerial Documentation that the way to open a COM Port is as below:
import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windows and I get an error for the following line:
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
This could be what you want. I'll have a look at the docs on writing.
In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
On Windows, you need to install pyserial by running
pip install pyserial
then your code would be
import serial
import time
serialPort = serial.Serial(
port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass
to write data to the port use the following method
serialPort.write(b"Hi How are you \r\n")
note:b"" indicate that you are sending bytes

How to read data from serial port? Python

Hi please bear my basic question as I am new to python.
I am trying to read data from serial port. Basically serial port is a USB port converted to serial port virtually. I am using arduino.
First i tried this code:
while(True):
ser=serial.Serial('COM6',9600)
bytoread=ser.inWaiting()
val=ser.read(bytoread)
But it gave me error.
Permission Error(13,Access is denied, none 5)
But when i changed my code to
while(True):
ser=serial.Serial()
ser.baudrate=19600
ser.port='COM6'
ser
ser.open()
bytoread=ser.inWaiting()
val=ser.read(bytoread)
Permission error did not come but program is always busy connecting the port. I waited for many minutes but it never moved forward. What I am doing wrong here?
you can do something like :
import serial
ser = serial.Serial('COM6', 9600, timeout=None)
while True:
data = ser.readline()
you can't put ser = serial.Serial('COM5', 9600, timeout=None) in your while loop because it will permanently (re)create the connection...

Can't receive reply using PySerial but hyperterminal works

I have a device (Pololu Wixel) that I'm trying to communicate with using a serial connection over USB. Hyperterminal works fine but I'm trying to use Python for more flexibility. I can send commands to the device, but when I try to receive all I get is the command I just sent. However, if I open Hyperterminal, I'll receive the reply there to the command sent from the script. My code is below. I'm at a bit of a loss and it seems like this should be fairly straightforward. I appreciate any help.
import serial
import time
'''
Go through 256 COM ports and try to open them.
'ser' will be the highest port number. Fix this later.
'''
for i in range(256):
currentPort = "COM" + str(i+1)
try:
ser = serial.Serial(currentPort,baudrate=115200,timeout=5)
print("Success!!")
print(ser.name)
except:
pass
print(ser.isOpen())
str = "batt" #Command to request battery levels.
ser.write(str.encode())
x = ser.inWaiting()
print(x)
while ser.inWaiting() > 0:
out = ser.readline()
print(out.decode())
Add a break after finding an active port,
Try passing a different eol value to readline(), "\r" or "\r\n".

Raspberry Pi is stuck when no char is received on the serial port

I am using an XBee module connected to my RPI, serial communication is established between both, the problem is my code gets stuck if there is no data present by the XBee, is there a away to solve this, I tried timeout but wasn't successful.
code:
ser = serial.Serial (
port = "/dev/ttyAMAO",
baudrate = 9600,
parity = serial.PARITY_NONE,
stopbits = serial,STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 0
)
ser = serial.Serial("/dev/ttyAMAO")
for c in ser.read():
l.append(c)
ser.read()
is a blocking call it is probably better to check if there is anything there to read first
if ser.inWaiting(): #only true if there is data waiting to be read
for c in ser.read():
....
or if you want your serial thread to run in parallel to your main program (ie. dont block user interface ever at all..) you should maybe look into something like twisted or asyncio
although typically with serial you are working with some device that wants 2-way communication, usually initiated with a query to the serial device, and you do want to actually block until you get a response. I will usually make a class to handle this for me
class MySerial:
def __init__(self,port,baudrate):
self.ser = serial.Serial(port,baudrate)
def query(cmd,terminal_char="\r"):
self.ser.write(cmd)
return ''.join(iter(ser.read,terminal_char))
s = MySerial("COM9",11200)
result = s.query("get -temp\r")
print result
this will accumulate an entire response until the specified terminal character is recieved

Categories

Resources