esp8266 and cp2102 don't work with python serial - python

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.

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.

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 send/receive data via HC-12/UART in Python

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)

using PySerial don't work until port is opened with minicom

I developed a plugin for Domoticz on a RPi3B+. This plugin is in Python.
I want to send commands to a Arduino board using a USB serial port.
The plugin opens the serial port, sends a command and closes the serial port. It works well except after a reboot.
After a reboot, the port is open, and the command seems to be sent to the Arduino, but it doesn't understand it, just as if the baud rate were wrong. Arduino's Rx LED is blinking.
If I open the serial in parallel using minicom and exit minicom without resetting the parameters, then the plugin starts working properly.
Here's my code:
serialCmd = "gpio sh" + str( shutterId ) + "_" + order +" on for " + str( PULSE_DURATION_MS ) + "\r"
Domoticz.Debug( "Serial command : " + serialCmd )
# open serial port
try:
Domoticz.Debug( "Opening serial port : " + Parameters["SerialPort"] )
serialPort = serial.Serial( port = Parameters["SerialPort"],
baudrate = 115200,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = 1,
xonxoff = False,
rtscts = False,
dsrdtr = False )
except:
serialPort = None
if serialPort:
serialPort.write( serialCmd.encode( 'utf-8' ) )
serialPort.close()
serialPort = None
The serial port is /dev/ttyUSB0.
If I try to use exclusive = True in serial.Serial(...), it fails to open the port, as if the port were already open.
Another strange thing: when the Arduino board reboots, it sends some information to the serial port.
I can't read it with the plugin in Python with PySerial, but I can read it with minicom.
If I close minicom with resetting the parameters, each time I open minicom this information is read by minicom (without resetting the Arduino board) as if the input buffer has never been read, and the Python plugin still doesn't work.
How do I solve the problem?
This issue was because of Arduino nano schematic where DTR signal is connected to the reset signal which makes the Arduino to reset each time the serial port is open. This post made me search the right thing on the internet. That's why opening minicom and closing without resetting the port makes it work...
When the serial is not used anymore by a process the DTR line is reset so next time a process open the serial port the DTR is driven which makes the Arduino reboot.
A way to fix it is to modify the board or two disable the DTR handling. This can be done by dsiable the HUPCL bit of the terminal lib.
Some people manage to fix it with pySerial but it does not work for me so I had to do as below...found here and here.
import serial
import termios
port = '/dev/ttysUSB0'
f = open(port)
attrs = termios.tcgetattr(f)
attrs[2] = attrs[2] & ~termios.HUPCL
termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
f.close()
se = serial.Serial()
se.baudrate = 115200
se.port = port
se.open()

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

Categories

Resources