How to run PuTTY serial commands in Python/ PySerial - python

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.

Related

Communicate with a terminal using pySerial

I have a terminal which I connect to with serial communication, and I want to read from it and write to it some commands I prepared in advance in a string array
Using pySerial, I need to write a code that will read the lines with a stop condition which is a wait from the console for input from the user, and then write the commands from the array
Just want to clarify, it's like an automatic PuTTY, and no I can't connect to the terminal through ssh, and no I can't bood the machine's terminal since it's not a pc
here is what i tried:
import serial
Baud_Rate = 9600
Ser = serial.Serial('COM4', Baud_Rate)
while Ser.isOpen():
input('Error: Ser is already open, please close it manually. if the port is
closed, press enter\n')
try:
Ser.close()
except serial.serialutil.PortNotOpenError:
pass
Ser.open()
Serial_com = [] #a str array with the relevant commands
for i in range(len(Serial_com)):
ter = Ser.readline()
while ter != 0xaf:
#print(str(ter))
print(str(ter.decode('utf-8').rstrip('\r\n')))
ter = Ser.readline()
sleep(1)
if i == 0:
print('login: root')
Ser.write(bytes("root", encoding='utf-8'))
else:
print('\n\n\n\n\nroot # Ser: ~ # ' + str(Serial_com[i]))
Ser.write(bytes(Serial_com[i], encoding='utf8'))
I realized that once the serial port is waiting for the python code (or the user) to write commands, that it sends the character 0xaf. It might be a coincidence, but still I wrote that as a stop condition for the reading from the terminal
the code can read from the serial port, but once it needs to write to the serial port it won't proceed
I can't share the rest because it's confedencial for a project

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

serial port getting engaged after reading single command in 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.

Python PySerial changing settings on timeout

I have a question about Python and PySerial.
On my Raspberry Pi i want to read a serial port from a device. I got 2 types of devices i want to read from. They both got different settings:
ser = serial.Serial()
ser.baudrate = 9600
ser.bytesize=serial.SEVENBITS
ser.parity=serial.PARITY_EVEN
ser.stopbits=serial.STOPBITS_ONE
ser.xonxoff=0
ser.rtscts=0
ser.timeout=20
ser.port="/dev/ttyUSB0
and:
ser = serial.Serial()
ser.baudrate = 115200
ser.bytesize=serial.EIGHTBITS
ser.parity=serial.PARITY_NONE
ser.stopbits=serial.STOPBITS_ONE
ser.xonxoff=1
ser.rtscts=0
ser.timeout=20
ser.port="/dev/ttyUSB0
This is the code to read the serial port:
try:
ser.open()
except:
sys.exit ("Error opening %s." % ser.name)
t_count = 0
while t_count < 20:
t_line = ''
try:
t_raw = ser.readline()
except serial.SerialException:
sys.exit ("Serial port %s could not be read." % ser.name )
t_str = str(t_raw)
t_line = t_str.strip()
print (t_line)
t_count += 1
try:
ser.close()
except:
sys.exit ("Oops %s. Program aborted. Could not close serial port." % ser.name )
So when i connect to a device with 115200 but the device runs 9600, i get timeouts ofcourse. But in my program it will just time out twenty times (times the for loop will run), and no exception to be thrown. Not even just before the program exits after looping 20 times. No error message nothing.
What i want to achieve is the following, i want to make the python script self detecting what he is connected to. When the readline() times out 20 times it should change settings. (by running another function or something).
I cant check if the readline returns something empty, because there are empty lines in the serial message.
Is there any way to get the right exception? Or any other smart way to solve this?
(By the way, i am sure the settings work. As i tested them both and run fine.)
Thanks in advance.
Cheers!
Easiest way would be to create a handshake function,
send something with one serial handler that you know the device will respond to correctly. If the answer is jibberish then change the handler and try the other one until you succceed.

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.

Categories

Resources