Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Can someone please show me a full python sample code that uses pyserial, i have the package and am wondering how to send the AT commands and read them back!
Blog post Serial RS232 connections in Python
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
use https://pythonhosted.org/pyserial/ for more examples
http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
#write data
ser.write("AT+CSQ")
print("write data: AT+CSQ")
time.sleep(0.5) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.
Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.
Related
I am trying to use a python script to control a rotating valve. I am able to do so through PuTTY but not using my script. Code is shown below. I also included PuTTY settings and a link to the valve positioner user manual that gives example commands.
import serial
ser = serial.Serial()
ser.port = 'COM7'
ser.baudrate = 9600
ser.bytesize = serial.SEVENBITS
ser.parity = serial.PARITY_ODD
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))
out = ser.readline()
print('Receiving... ' + str(out))
The manual that you link to says that it needs a <CR> at the end of each command.
Also your putty configuration says that it adds crlf.
You could change your code like this:
ser.write(str.encode(cmd + '\r\n'))
With code below i'm getting unwanted symbols/characters. As an example, in this case I should be only receiving "boot.last" but instead i'm getting "[0;0mboot.last [0m"
ser = serial.Serial(
port='COM1',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
ser.isOpen()
print ('Enter your commands below.\r\nInsert "exit" to leave the application.')
userin=1
while 1 :
# get keyboard input
userin = input(">> ")
# Python 3 users
# input = input(">> ")
if userin == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(userin.encode('utf-8') + '\r\n'.encode('utf-8'))
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1).decode('ascii')
if out != '':
print(">>" + out)
I want to write a simple code in python to send USSD codes to a GSM modem (D-link DWM-157) and receive their results and store them in variables. I can connect to the modem with minicom and also miniterm.py. But the problem is that they need a terminal to send/receive AT commands to the modem. I don't want an extra terminal. I also use the following code to send a simple AT command but when I run the code nothing happens:
import serial, time
def serial_def():
ser = serial.Serial()
ser.port = "/dev/ttyUSB2"
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2
ser.open()
if ser.isOpen():
print(ser.name + ' is open...')
ser.write("AT"+"\r\n")
time.sleep(1)
out=''
while True:
out += ser.read(1)
print (out)
ser.close()
if __name__ == '__main__':
serial_def()
When I run the code I only see the following:
/dev/ttyUSB2 is open...
Any help is appreciated.
I'm still new in python so please bear with me, so I'm trying to write a script with python2-pyserial but I keep getting error Attempting to use a port that is not open Here's the script:
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB2"
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
print ("Port has been opened")
except Exception, e:
print ("error open serial port: ") + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()
ser.write("ATI")
print("write data: ATI")
time.sleep(1) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
#pass
ser.close()
except Exception, e1:
print ("error communicating...: ") + str(e1)
else:
print ("cannot open serial port ")
I've tried to run the script with sudo python2 ser but I still have the same error. How do I fix it ?
The first part of your code is wrong, you're making the wrong attributions for ser. Try the following way:
ser = serial.Serial(
port = "/dev/ttyUSB2",
baudrate = 115200,
bytesize = serial.EIGHTBITS,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
timeout = 1,
xonxoff = False,
rtscts = False,
dsrdtr = False,
writeTimeout = 2
)
On my environment, the port was already open after that, but if it isn't you can try to open it:
ser.open()
ser.isOpen()
And you have to be sure that this is not a virtual port on your pc if it is, you will have to change this:
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
For this:
ser.rtscts = True
ser.dsrdtr = True
Check out this issue for more info
I have raspberry PI B+ with connected Telegesis ZigBee module(ETRX3 USB sticks) via USB. Using commands:
debian:~# stty -F /dev/ttyUSB0 -raw ispeed 19200 ospeed 19200
debian:~# cat < /dev/ttyUSB0 &
debian:~# echo "ATI" > /dev/ttyUSB0
the ZigBee module executed ATI command and I can see the correct output:
Telegesis ETRX357
R308C
OK
The same thing I want to do with python script. I was written python script with code:
#!/usr/bin/env python
# based on tutorials:
# http://www.roman10.net/serial-port-communication-in-python/
# http://www.brettdangerfield.com/post/raspberrypi_tempature_monitor_project/
import serial, time
SERIALPORT = "/dev/ttyUSB0"
BAUDRATE = 19200
ser = serial.Serial(SERIALPORT, BAUDRATE)
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
#ser.timeout = 0 #non-block read
ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 0 #timeout for write
print 'Starting Up Serial Monitor'
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
ser.write("ATI")
print("write data: ATI")
time.sleep(0.5)
numberOfLine = 0
while True:
response = ser.readline()
print("read data: " + response)
numberOfLine = numberOfLine + 1
if (numberOfLine >= 5):
break
ser.close()
except Exception, e:
print "error communicating...: " + str(e)
else:
print "cannot open serial port "
and get results as on the screen
ATI
but I want to command be execute by ZigBee module, as like in shell commands. What am I doing wrong?
you need to append an end-of-line to your write()
ser.write("ATI\r\n")
you should change the timeout to:
ser.timeout = None
Otherwise readline() will return after 2 seconds, even if nothing has been read.