serial port getting engaged after reading single command in python - python

I am making a connection with python using pyserial with a UART port. As I send the command using serial.write my output is received but my serial port does not break connection. As I need to send a second command also to receive the output. Please guide me on this.
I have also used ser.close still I am not able to close the port.
import serial
ser = serial.Serial(
port='COM5', \
baudrate=9600, \
parity=serial.PARITY_NONE, \
stopbits=serial.STOPBITS_ONE, \
bytesize=serial.EIGHTBITS, \
timeout= 10)
print("connected to: " + ser.portstr)
ser.write(b'\reeprom\r')
seq = []
count = 1
while True:
for c in ser.readline():
seq.append(chr(c)) # convert from ANSII
joined_seq = ''.join(str(v) for v in seq) # Make a string from array
if chr(c) == '\n':
print("Line " + str(count) + ': ' + joined_seq)
seq = []
count += 1
break
ser.close()
Can you please guide what is going wrong. I am expecting that I should get my output of the fired command to UART and then code should exit rather than continue running. Also I wanted to know if this works can I again make connection and fire the second command to UART. Please help me on this.

Related

How to run PuTTY serial commands in Python/ PySerial

I'm trying to communicate with probe by serial COM port. Manufacturer make some commands in PuTTY ec. change measurement units or read some values. I write peace of code in python but I received nothing or I don't know what I recieved. Here is PuTTY configuration
Next is example of commands from manufacturer for PuTTY.
Here is code in PuTTY terminal:
My code in Python:
import serial
ser = serial.Serial()
ser.port = 'COM5'
ser.baudrate = 19200
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.xonxoff = 0
ser.rtscts = 0
ser.dsrdtr = 0
ser.stopbits = 1
ser.timeout = 1
ser.open()
if ser.isOpen():
print(ser.name + ' is open...')
while True:
cmd = input("Enter command or 'exit':")
if cmd == 'exit':
ser.close()
break
else:
# ser.write(cmd.encode('ascii'))
# ser.write(bytes(cmd, 'utf-8'))
ser.write(str.encode(cmd + '\r\n')) #
out = ser.readline().decode("utf-8").strip()
print('Receiving... ' + str(out))
And here is what I received:
Enter command or 'exit':UNIT
Receiving...
Enter command or 'exit':exit
Edit:
you can pass in a timeout value to your serial instance. Try increasing this although i don't think thats the problem here. More likely the device your communicating with doesn't send newline / carriage return characters at the end of it's messages. In that case you'd have to use read(). But you should be able to check what characters are sent by the device by checking a box that says something like display newline characters or display CR/LF. I'm not sure if putty supports this, since i don't really use it as a serial monitor, but it probably does.

Unable to read from serial in c#, but works in python

I am unable to read from serial port in C#, all of the settings are matching (baud, sbit etc...), the code actually sends the SCPI code to my gadget, but it is not responding (the gadget).
I have a very similar code in Python 3.7 and that is working correctly, with the same gadget and with every other.
So this is the C# code:
SerialPort com = new SerialPort("COM22",9600,Parity.Even,7,StopBits.Two);
com.Open();
Thread.Sleep(100);
com.DiscardOutBuffer();
com.DiscardInBuffer();
Console.Write("SCPI: ");
string cmd = Console.ReadLine();
com.Write(cmd + "\n");
Thread.Sleep(2000);
string answ = com.ReadExisting();
Console.WriteLine("The answer "+answ);
com.Close();
Here in C# I have also tried ReadChar(), ReadByte() and ReadLine()...
And also I have tried to change HandShake.
And here goes the Python code:
import time
import serial
while 1:
try:
comPort = input("Insert COM port num to use: ")
ser = serial.Serial(
port='COM' + comPort,
baudrate=9600,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
) # serial port settings
ser.isOpen()
break
except Exception:
print("Bad COM port. Try again.")
print('Enter your commands below.\nInsert "exit" to leave the application.')
while 1:
cmd = input("Insert your command: ") # insert the commands
if cmd == 'exit':
ser.close()
exit()
else:
ser.write(str.encode(cmd + '\n')) # send the character to the device
out = " "
time.sleep(2) # wait one second before reading output (give device time to answer)
while ser.inWaiting() > 0:
out += ser.read(1).decode("ascii")
print(">>" + out) # output the answer
As you can see they are very similar, with the same waiting time...

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".

esp8266 and cp2102 don't work with python serial

esp8266 and cp2102 don't work! Why?
import serial
sp="/dev/ttyUSB0"
port = serial.Serial(sp)
while True:
port.write("AT+RST")
rcv = port.read(10)
print rcv
I pressed "AT+RST"[Enter] and don't have "READY" after it.
Make sure you include CRLF (\r\n) characters at the end of your command. I lost a day messing with this before I figured that out. I got the local echo back of the command but since I never sent a \r\n I would not get any more data. Here is what works for me as a basic terminal in Python using pyserial:
import serial
import time
ser = serial.Serial('/dev/tty.usbserial-A8004xaO', 115200, timeout=2.5)
while True:
cmd = raw_input("> ");
ser.write(cmd + "\r\n")
ret = ser.read(len(cmd)) # eat echo
time.sleep( 0.2 )
while ( ser.inWaiting() ):
ret = ser.readline().rstrip()
print ret
You aren't setting a baud rate when opening the serial port. The default is probably not appropriate for the ESP8266.

Opening serial ports, Pyserial

I'd like to connect with Lake Shore Temperature Controler M331 via RS232, and I've got a little problem with that. When i give a "command" it still waits for another one instead of sending it to my device. Here is my code:
import serial
import time
port = serial.Serial(15)
print "Opening serial port: " + port.name
out = []
command = raw_input('Command: ')
if command == 'exit':
port.close()
exit()
else:
port.write(command)
time.sleep(1)
out.append(port.read(8))
if len(out) == 0:
print ':('
else:
print out
port.close()
What is wrong with my code?
found it sorry for interrupting ;) there should be:
port.write(command +'\r')

Categories

Resources