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...
Related
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.
I have this code which im using to connect to a printer and send it commands. It works perfectly until it gets to the while loop, it just cant get out of it. The output prints the first few lines expected in serial than just waits until while loop goes false. how do i get out of the loop?
import serial
import os
import time
ser = serial.Serial('/dev/ttyUSB0', 115200) # open serial port
print("Device Name: " + ser.name)
while True:
response = ser.readline().decode('utf-8')
print(response)
time.sleep(1)
The whole point of a while True: loop is that there is no stop condition. This means that it will keep going until you manually stop your program.
What you can do is add a break statement when you don't read anything anymore.
And don't forget to use a timeout on your serial so it doesn't hang forever waiting for new data:
import serial
import os
import time
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=10) # open serial port
print("Device Name: " + ser.name)
counter = 0
while counter < 10:
response = ser.readline().decode('utf-8')
print(response)
if response == "":
break
time.sleep(1)
With this, it will read everything available then wait 10 seconds for additional data.
If there is no more data, it will return an empty string (no bytes read) and break from the loop.
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.
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.
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')