I've a displacemente measurement and I want that Python give me the values, but I do not know, How receive the data.I use this code, and give me the following error - TypeError: can't concat bytes to str.
`import serial
port = "COM3"
baud = 115200
ser = serial.Serial(port, baud, timeout=1)
# open the serial port
if ser.isOpen():
print(ser.name + ' is open...')
while True:
cmd = input("Enter command or 'exit':")
# for Python 2
# cmd = input("Enter command or 'exit':")
# for Python 3
if cmd == 'exit':
ser.close()
exit()
else:
ser.write(cmd.encode('ascii','strict')+'\r\n')
out = ser.read()
print('Receiving...'+out)
`
write(... does only accept binary data.
Documentation pySerial API
write(data)
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g.'hello'.encode('utf-8').
Related
So I'm receiving data from a serial port using pySerial. I've a very simple code that reads the first byte, check if it's the start byte ( 0x02 in my case) and then read until it finds the end byte ( 0x03 in my case).
Config the serial communciation
port = 'COM3'
baud = 38400
ser = serial.Serial(port, baud, timeout=0)
if ser.isOpen():
ser.close()
ser.open()
ser.reset_input_buffer()
ser.reset_output_buffer()
The main loop is inside a while True staement as below.
while True:
data = ""
data_raw = ser.read(1)
if data_raw == b'\x02':
data_raw = ser.read_until(b'\x03')
print(str(data_raw))
ser.reset_input_buffer()
ser.reset_output_buffer()
time.sleep(.5)
The issue is that, for some reason, the read_until() actually reads only the first bye while the data I'm receiving from the serial port are actually b'\x02\xff\x9c\x81E1\x03\'
After reading correctly the \x02 the read_until() statement just read only the next \xff and I can't understand why
It seems a bug never fixed by the pySerial module itself https://github.com/pyserial/pyserial/issues/181
Using timeout=None in serial.Serial() resolved the issue
I would like to create a Python programm like a terminal to send some request with Pyserial.
But when I send a request like "dataid 60000 get value" it show me an error message like :
TypeError: unicode strings are not supported, please encode to bytes: 'dataid 60000 get value'
I tried to use .encode but no result..
See below my code :
#Modules
from base64 import encode
import serial
port = "COM5"
baud = 115200
#Serial port configuration
com = serial.Serial(port, baud, timeout=1)
if com.isOpen():
print(com.name + ' is open...')
#Print output
while True:
cmd = input("Enter command or 'exit':")
if cmd == 'exit':
com.close()
exit()
else:
com.write(cmd)
out = com.read()
print('Receiving...'+out)
Thanks in advance ! :)
To send command over serial/console port, use:
com.write(cmd.encode("utf-8"))
or
com.write(b"string")
This encodes your input to bytes.
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 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...
I am trying to send this command ":01050801FF00F2" over serial in python 2.7 , with no success.
The code that i use is :
import serial, sys ,socket
from time import sleep
port = "COM9"
baudRate = 9600
try:
ser = serial.Serial(port, baudRate, timeout=1)
if not ser.isOpen():
ser.open()
except Exception, e:
print("Error opening com port. Quitting."+str(e))
sys.exit(0)
print("Opening " + ser.portstr)
#this is few ways i am trying to send with
c = '01050801FF00F2'
ser.write(c.encode('utf-8'))
sleep(3)
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
c = ':01050801FF00F2'
ser.write(c.encode('hex'))
sleep(3)
ser.write(':01050801FF00F2')
If those are hex values, this should work:
c = '\x01\x05\x08\x01\xFF\x00\xF2'
ser.write(c)
Have you tried sending the command using bytearray?
Perhaps you could try:
ser.write(b':01050801FF00F2')
or
ser.write(':01050801FF00F2'.encode())