I'm trying communicate with STM32L152RB board through COM port 4 which accepts commands from COM4 and displays result in terminal using this code but it's not working ... I'm new to python please let me know what I'm doing wrong.
#Global Variables
ser = 0
def init_serial():
COMNUM = 4 #Enter Your COM Port Number Here.
global ser #Must be declared in Each Function
ser = serial.Serial()
ser.baudrate = 9600
ser.port = COMNUM - 1 #COM Port Name Start from 0
#ser.port = '/dev/ttyUSB0' #If Using Linux
#Specify the TimeOut in seconds, so that SerialPort
#Doesn't hangs
ser.timeout = 10
ser.open() #Opens SerialPort
# print port open or closed
if ser.isOpen():
print 'dis' + ser.portstr
init_serial()
temp = raw_input('Type what you want to send, hit enter:\r\n')
ser.write('dis') #Writes to the SerialPort
while 1:
bytes = ser.read() #Read from Serial Port
print 'You sent: ' + bytes #Print What is Read from Port
Related
Im trying to read the signal strength/quality from gsm modems, so i used this AT+CSQ command.
from time import sleep
import serial
from curses import ascii
ser = serial.Serial()
ser.port = "COM10"
ser.baudrate = 9600
ser.open()
print(ser.write('AT+CSQ=?'.encode("ascii")))
ser.write returns the number of bytes written (on the port).
(https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.write)
You need to call ser.read afterward to read the answear.
Something like :
from time import sleep
import serial
ser = serial.Serial()
ser.port = "COM10"
ser.baudrate = 9600
ser.open()
try:
res_write = ser.write('AT+CSQ=?'.encode("ascii"))
sleep(0.01)
res_read = b""
while ser.inWaiting() > 0:
res_read += ser.read(1)
finally : # ensure you close the use of the port in case of crash
ser.close()
print(res_read.decode("ascii"))
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'))
I am trying to make two beaglebone microcontrollers to communicate with each other using UART.
When there is an input by user on TX side of microcntroller, RX side has to get that input but my RX side is missing some of the data sent by TX side.
Here is my TX side code
import serial
import time
UART.setup("UART1")
ser = serial.Serial(
port = "/dev/ttyO1", #enable UART1
baudrate = 9600, #Set Baudrate = 9600
)
time.sleep(3)
ser.close() #Close serial port
ser.open() #Open serial port
ser.flushInput() #Flush the input of serial port
ser.flushOutput() #Flush the output of serial port
print ser.name #Print serial port being used in the beginning
while True: #Set the infinite loop for the input
print('enter the data')
dataToSend = raw_input()
tempData = str(dataToSend )
ser.write(tempData)
And this is my RX side code.
import Adafruit_BBIO.UART as UART
import serial
import time
UART.setup("UART1")
ser = serial.Serial(
port = "/dev/ttyO1", #enable UART1
baudrate = 9600 #Set Baudrate = 9600
)
time.sleep(3)
ser.close() #Close serial port
ser.open() #Open serial port
ser.flushInput() #Flush the input of serial port
ser.flushOutput() #Flush the output of serial port
msg_count = 0
slaveAddress = '1'
addressConfirmed = False
print ser.name #Print serial port being used in the beginning
while True:
size = ser.inWaiting()
if size > 0 :
rawData = ser.read(size)
rawData = str(rawData)
print(rawData)
else:
pass
Can someone please tell me what the problem is with my code?
Thank you
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.
I'm sending a list of values (e.g. 80,539,345,677) from Arduino to a Python app running on my RPi. I have not been successful in extracting the values and assigning them to respective variables or objects in the app.
Here's my code:
def read_values():
#if DEBUG:
print "reading arduino data"
ser = serial.Serial('/dev/ttyUSB0', 9600)
print "receiving arduino data"
ser_line = ser.readline()
print ser_line
ser.close()
ser_list = [int(x) for x in ser_line.split(',')]
ambientLight = ser_list[1]
print ambientLight
return ambientLight
What I'm getting from Python is:
reading arduino data
receiving arduino data
80,477,82,2
Traceback (most recent call last):
File "serialXivelyTest4c.py", line 77, in <module>
run()
File "serialXivelyTest4c.py", line 63, in run
ambientLight = read_values()
File "serialXivelyTest4c.py", line 27, in read_values
ser_list = [int(x) for x in ser_line.split(',')]
ValueError: invalid literal for int() with base 10: '8254\r80'
You can see that I'm getting values, but that they're being truncated. Can anyone please tell me where I'm going wrong here. Thanks so much.
I've never used an Arduino but here's how I read from serial with a different board. I used serial.
import streamUtils as su # see below
ser = su.connectPort("/dev/tty.SLAB_USBtoUART") # make sure you have the right port name
data = ""
while True:
try:
data = data + ser.read(1) # read one, blocking
time.sleep(1) # give it time to put more in waiting
n = ser.inWaiting() # look if there is more
if n:
data = data + ser.read(n) # get as much as possible
# I needed to save the data until I had complete
# output.
if data:
# make sure you have the whole line and format
else:
break
except serial.SerialException:
sys.stderr.write("Waiting for %s to be available" % (ser.name))
sys.exit(1)
sys.stderr.write("Closing port\n")
ser.close()
Here's the streamUtils.connectPort():
import serial
def connectPort(portname):
# connect to serial port
ser = serial.Serial()
ser.port = portname
ser.baudrate = 9600
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.bytesize = serial.EIGHTBITS
ser.timeout = 15 # need some value for timeout so the read will end
try:
ser.open()
except serial.SerialException:
sys.stderr.write("Could not open serial port %s\n" % (ser.name))
sys.exit(1)
return (ser)