read write communication pySerial - python

Hello I have trouble with read/write from or to device. I wanted to make a serial connection via rs 485 (half-duplex) . When I call read and write functions they didnt receive a data. Anyone know what I do wrong?
def Transmission(ser,data):
if ser.isOpen():
try:
print(data)
ser.flushInput()
ser.flushOutput()
ser.rtscts = True
ser.write(data)
time.sleep(0.1)
numOfLines = 0
print("write: " + data)
while True:
response = ser.readline()
print("read data: " + response)
ser.rtscts = False
numOfLines = numOfLines + 1
if(numOfLines >= 5):
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
return response
Terminal didnt show receiving data:
powah
write: powah
read data:
read data:
read data:
read data:
read data:
I tried to write with read in the loop (with changing ser.rtscts). How to fix that problem? Thank You

Related

Python - Getting output of socket

I am trying to get the output after the lolimessage was sent but i get no output
try:
xmr = ''
data = s.recv(1024)
d = data.decode("UTF-8")
xmr += d
if "loli" in xmr:
s.send(lolimessage + enter)
print("Loli Sent")
else:
print("loli NOT sent")
except:
s.close()
try:
xmr = ''
data = s.recv(1024)
d = data.decode("UTF-8")
xmr += d
print(xmr)
except:
print("fail to print")
s.close()
The loli part works and prints out data but on the 2nd try i get "fail to print", can any1 plz help
s.send(lolimessage + enter)
send it in bytes with encoding
s.send(bytes(lolimessage + enter, "utf-8"))

Python script crashes randomly for unknown reason

I am using the following script as the basis for a homebuilt energy monitoring system. The script serves as a gateway between an arduino based receiver connected to the serial port and passes it on through MQTT as well as a http POST. The script is intended to run indefinitely. However it crashes at random intervals, anywhere from an hour to a week. I cannot figure out why. Any pointers on how to determine why and how to log the error would be appreciated. Here is the script:
import time
import datetime
import requests
import paho.mqtt.publish as publish
#import csv
import logging
logging.basicConfig(level=logging.ERROR, filename='serial-read.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
device = '/dev/ttyUSB0' #this will have to be changed to the serial port you are using
data = ""
pieces = ""
while True:
while True:
try:
receiver = serial.Serial(device, 57600)
receiver.flushInput()
except serial.SerialException:
print "cannot connect. will try again..."
time.sleep(10)
else:
break
try:
data = receiver.readline()
#print (data)
#print repr(data)
#with open ("data_log.csv","a") as f:
#writer = csv.writer(f,delimiter=",")
#writer.writerow([time.time(),data])
pieces = data.split(" ")
try:
nodeid = int(pieces[0])
except ValueError:
pass
try:
data1 = int(pieces[1])
data2 = int(pieces[2])
data3 = int(pieces[3])
data4 = int(pieces[4])
except IndexError:
pass
#print nodeid
if nodeid == 6:
#print "Power:"
Irms = data3 + data4
print Irms
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
localtime = "'" + localtime + "'"
#print localtime
payload = {"timestamp" : localtime, "Irms" : Irms}
r = requests.post('http://www.********.ca/*****.php', params=payload)
#print(r.url)
publish.single("myHome/energy/power", Irms, hostname="192.168.1.120")
elif nodeid == 2:
temp = float(data1)/10
#print "temp:"
#print temp
hum = data3
publish.single("myHome/garage/temperature", temp, hostname="192.168.1.120")
publish.single("myHome/garage/humidity", hum, hostname="192.168.1.120")
temphum = str(temp) + " " + str(hum)
publish.single("myHome/garage/temphum", temphum, hostname="192.168.1.120")
#print temphum
except serial.serialutil.SerialException:
print "no device connected. Please reconnect device..."
receiver.close()
time.sleep(5)
Thank you!
Baobab
Your second try statement catches the following exception:
except serial.serialutil.SerialException:
But what if the block of code generates a different exception? The script will exit. Add a second except, as in the first try loop, to catch any other exceptions, and print them to your log.

Connecting python script to microcontroller

I am trying to send textual commands to a microcontroller through usb serial port (ttyUSB0), the controller should respond with 'Y' or 'N' and execute the command. Commands are given in the following form '#01a' where the # is beginning symbol 0 is position for A channel and 1 position for B channel and 'a' is checksum of A+B.
I'm stuck and a beginner in python so any help is welcome and appreciated.
p.s. when I connect using putty everything works as expected
also the OS is Ubuntu 16.04 LTS
This is my code:
import time
import serial
import binascii
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=19200,
)
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
AT = chr(int('1000000',2))
A = chr(int('100000',2))
B = chr(int('100000',2))
AB = chr(int('1000000',2))
input = AT + A + B + AB
print input
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(input)
# 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):
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "

python writing byte-by-byte to serial port didn't work

As discussed before in the forum reading problem is being solved but now getting write problem. I want to write some hexadecimal address to the serial port. the address looks like:
000062240
000062A4B
000062244
000062245
000062D50
00006225E
00006A25F
I want to write them byte by byte with the delay of 0.01 sec. To write I do:
Before writing I need to write N and that works perfectly. After C I need to write the address. I put the inner loop in the text file to read the address. But ser.write(line[line1-1]) give the string can not combine with int error. Any solution?
for line1 in range(1,8):
ser.write(line[line1-1])
time.sleep(0.01)
The writing code :
with open('lut.txt', 'r') as f:
for line in f:
#print line
ser.write('N')
time.sleep(0.01)
ser.write(' ')
time.sleep(0.01)
ser.write('C')
time.sleep(0.01)
for line1 in range(1,8):
ser.write(line[line1-1])
time.sleep(0.01)
line+=1
time.sleep(0.01)
For the reference complete code.
import serial, time
from addresstable import *
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 38400
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.xonxoff = False
ser.rtscts = False
ser.dsrdtr = False
number_address = 10
number_char = 9
timeout=1
#f=open('lut.txt','r')
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
# reading
max_packet = 20
lines = 0
while True:
byteData = ser.read_until('\r',max_packet)
newdata=str(byteData)
print newdata.strip()
ser.write('I')
time.sleep(0.01)
# writing
with open('lut.txt', 'r') as f:
for line in f:
#print line
ser.write('N')
time.sleep(0.01)
ser.write(' ')
time.sleep(0.01)
ser.write('C')
time.sleep(0.01)
for line1 in range(1,8):
ser.write(line[line1-1])
time.sleep(0.01)
line+=1
time.sleep(0.01)
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
This is what I am doing now:
for line in f:
ser.write('N')
time.sleep(0.01)
ser.write(' ')
time.sleep(0.01)
ser.write('C')
time.sleep(0.01)
#for line1 in range(1,8):
line="line"+"0"
print len(line)
requ = binascii.unhexlify(line)
for i in requ:
ser.write(i)
time.sleep(0.01)
line+=1
time.sleep(0.01)
Problem solved with much simpler way. For future reference.
for i in line:
newdata=i
ser.write(newdata)
time.sleep(0.01)

Python serial port returing null string

Reading data from the serial port:
readline() in the below code return the null vector, the reading data from the serial port is hexadecimal number like AABB00EF the putty gives me the output means the communication is working but nothing works via python
here is the code:
#!/usr/bin/python
import serial, time
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
ser.baudrate = 115200
#ser.bytesize = serial.EIGHTBITS
#ser.parity = serial.PARITY_NONE
#ser.stopbits = serial.STOPBITS_ONE
#ser.timeout = None
ser.timeout = 1
#ser.xonxoff = False
#ser.rtscts = False
#ser.dsrdtr = False
#ser.writeTimeout = 2
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
#ser.flushInput()
#ser.flushOutput()
#time.sleep(0.5)
# numOfLines = 0
# f=open('signature.txt','w+')
while True:
response = ser.readline()
print len(response)
#f=ser.write(response)
print response
# numOfLines = numOfLines + 1
f.close()
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
readline will try to read until the end of the line is reached, if there is no \r or \n then it will wait forever (if you have a timeout it might work...) instead try something like this
ser.setTimeout(1)
result = ser.read(1000) # read 1000 characters or until our timeout occures, whichever comes first
print repr(result)
just use this code
ser = serial.Serial("/dev/ttyUSB0",115200,timeout=1)
print "OK OPENED SERIAL:",ser
time.sleep(1)# if this is arduino ... wait longer time.sleep(5)
ser.write("\r") # send newline
time.sleep(0.1)
print "READ:",repr(ser.read(8))
you can create a readuntil method
def read_until(ser,terminator="\n"):
resp = ""
while not resp.endswith(terminator):
tmp = ser.read(1)
if not tmp: return resp # timeout occured
resp += tmp
return resp
then just use it like
read_until(ser,"\r")

Categories

Resources