I'm tried to get the answer from a machine throught serial's com.
but i dont why i am receiving that i send!
with serial.Serial(port,
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
#timeout=0.5,
xonxoff=False,
rtscts=False,
dsrdtr=False
) as ser:
print(port,'opened!')
ser.reset_input_buffer()
o1='at+cgmr\r\n'
x=ser.write(o1.encode()) #without encode() error!
print('sended',x,'bytes','-->',o1)
sleep(1)
y=ser.readline(10) #ser.readline() is the same and read(10) as well
print('answer',y)
And the output is:
COM3 opened!
sended 8 bytes --> at+cgmr
respuesta b'at+cgmr\r\r\n'
Teorically i have to receive 'ok' or 'not ok'.
any idea?
Probably the device echoes back what it got and then sends its reply. Have you tried to increase the number of bytes you receive?
There is a chance that if you do y = ser.read(100) (with timeout enabled), you will get everything you asked for.
An alternative is to read exactly as many bytes as there are available:
y = ser.read(ser.in_waiting)
or
y = ser.read(ser.inWaiting())
(depending on the version of pyserial).
Related
If I use Putty to connect with serial to COM1, 1200 baud I get a black screen but when I type Ctlr-E on the keyboard I get the value that I'm looking to record. If I use serial.tools.miniterm and I type Ctrl-E on the keyboard I get the proper value. When I use the following code it seems as though I connect and there is nothing waiting in the buffer:
import serial
ser = serial.Serial(
port='com1',\
baudrate=1200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print(ser.flush())
print(ser.flushInput())
print(ser.reset_input_buffer())
print(ser.flushOutput())
print(ser.reset_output_buffer())
print(ser.in_waiting)
print(ser.out_waiting)
print(ser.readline())
print(ser.read())
print(ser.read(1))
ser.close()
I get back on screen:
None
None
None
None
0
0
b''
b''
b''
I was expecting one of these results to be the value I get in Putty and Miniterm.
What am I doing wrong? After connecting with Python can I send that same key sequence that is sent by Putty when I type Ctrl-E?
I figured out what was needed / missing partially due to a post from here on Oct 2nd, 2013 by Chaosphere2112. I need to both send an encapsulated \x05 (thanks barny) but also wait and then read the value in the buffer.
here is the code that worked in the end:
import serial
import time
ser = serial.Serial(
port='com1',\
baudrate=1200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
ser.write('\x05'.encode('utf-8'))
time.sleep(1)
read_val = ser.read(size=64)
if read_val != '':
print(read_val)
ser.close()
Thank you.
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)
I'm using raspberry pi 3 and this code to send a request to a device and receive the response from.
#!/usr/bin/python3.7
import socket # Import socket module
import thread
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
while True:
output += ser.read(1)
#time.sleep(0.1)
print "Reading... "+output.encode('hex')
It handles the response but there are missing bytes, it should receive a 56 bytes length string instead of 53.
This is the output:
a5030119010000010001000a20120118180130090100020505030117501701051421000301040120010516039833630004060104c200007d
There are 3 missing bytes
The serial configuration is what the manufacturer says in the documentation.
This device works well with my other application made in Delphi.
EXTRA
This is a comparison from my delphi app and this py script:
Delphi app
A5030119010000010001000A20120118180130090100020505030117501701051421000301040120010516039833630004060104C200007D
Python script
a503011901000001000100 1201181801300901000205050301175017010514210003010401 010516039833630004060104c200007d
The solution was to set the max byte to the serial.read() method
This should be related to the device work behavior
#!/usr/bin/python3.7
#sudo python /home/testing.py
import serial
import time
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=5
)
input = '5A03010d0a75'
print "Sending request... "+input
ser.write(input.decode("hex"))
print "Request sent."
output=""
time.sleep(1)
while ser.inWaiting() > 0:
output += ser.read(10) #setting it to 10 will fix this problem
print "Reading... "+output.encode('hex')
I have a rectifier outputting voltage and amperage information every 3 seconds. I installed python 2.7 and pySerial without a hitch. I am trying to get the following code to read data being sent at baud 2400, 7 data bits, even parity, and one stop bit. Other RS232 programs get it without a hitch. When I start the program from cmd I get a blinking underscore. What am I doing wrong?
import time
import serial
ser = serial.Serial(
port='COM3',
baudrate=2400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
while True:
message = ser.readline()
print(message)
time.sleep(3)
I'm dealing with a gm29 by Sony Ericsson.
The datasheet says that plugging the power is not sufficient to switch on the modem. It says:
activate the RS232 control line DTR, high for > 0.2s.
I'm writing some tests in python, but:
#!/usr/bin/env python
import serial
from time import sleep
socket = serial.Serial('/dev/ttyS0',
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1,
xonxoff=0,
rtscts=0
)
socket.setDTR(True)
sleep(3)
socket.setDTR(False)
try:
while True:
socket.write('AT'+chr(13));
sleep(1)
print "Reading"
print socket.readlines()
except:
socket.close()
does not works... I there a way to get DTR high in other ways? Let's say minicom or some other stuff? Or, easily, am I missing something?
Thanks in advance.
Ok, that was driving me mad. The clue is that the power supplier was "broken", or better, it works good testing with a tester, but plugging on the modem some wires moves and does not carry voltage...
Thanks anyway for the answer, marked as correct 'couse it was :D
There are several things that occur to me here.
1) the spec says that DTR is active low, so you may need to swap the true and false values to setDTR(), depending on who is confused here.
2) You are setting DTR to false after you wake the modem. This tells the modem to go offline, and ignore all input till it goes true again. Try the following:
import serial
from time import sleep
conn = serial.Serial('/dev/ttyS0',
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1,
xonxoff=0,
rtscts=0
)
# Wake Modem
conn.setDTR(True)
sleep(3)
conn.setDTR(False)
sleep(5)
# Start talking
conn.setDTR(True)
try:
while True:
conn.write('AT'+chr(13));
print conn.readline() # readlines() will probably never return.
finally:
conn.close()
3) socket is probably a bad name for your serial connection.