pyserial, if and file read - python

I have a stupid python problem.
I'm trying to read a line from a file everytime i get a 'READY' message from a serial connection so i wrote this :
import serial
from time import sleep
port = "/dev/tty.usbserial-A400fYTT"
speed = 57600
polarfile = 'polarfile.pg'
f = open(polarfile, 'r')
ser = serial.Serial(port, speed, timeout=0)
while True:
data = ser.read(9999)
if len(data) > 0:
if(data == 'READY'):
f.readline()
else:
sleep(0.5)
sleep(1)
ser.close()
But it doesn't work, however if i replace the if(data == 'READY' block by print data. I get the READY message.
Also i can read my file with f.readline()...
Thanks to give advice to a py newbie
--
edit :
Important info, the serial doesn't receive only "READY" message, but a bunch of other, but i want just to react when the "READY" messsage is received.

I just replace
data = ser.read(9999)
by
data = ser.readline(9999) which gives me the message line by line instead of second by second of input data and then replace
if( data == 'READY' ):by
if (data.startswith('READY')):
and now it works :)

Related

After changing from Python 2.7 to Python 3.7 data getting an additional letter?

I'm working on a program that receives a string from an Android app sent through WiFi, the program was originally written for Python 2.7, but after adding some additional functionalities I changed it to Python 3.7. However, after making that change, my data had an extra letter at the front and for the life of me I can't figure out why that is.
Here's a snippet of my code, it's a really simple if statement to see which command was sent from the Android app and controls Raspberry Pi (4) cam (v.2) with the command.
This part sets up the connections and wait to see which command I send.
isoCmd = ['auto','100','200','300','400','500','640','800']
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
brightness = 50
timelapse = 0
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print ('Waiting for connection')
tcpCliSock,addr = tcpSerSock.accept()
try:
while True:
data = ''
brightness = ' '
data = tcpCliSock.recv(BUFSIZE)
dataStr = str(data[1:])
print ("Here's data ",dataStr)
if not data:
break
if data in isoCmd:
if data == "auto":
camera.iso = 0
print ('ISO: Auto')
else:
camera.iso = int(data)
print ('ISO: '), data
When I start the program this is what I see:
Waiting for connection
#If I send command '300'
Here's data b'300'
Here's data b''
Waiting for connection
I'm not sure why there's the extra b'' is coming from. I have tested the code by just adding the "b" at the beginning of each items in the array which worked for any commands that I defined, not for any commands to control the Pi camera since well, there's no extra b at the beginning. (Did that make sense?) My point is, I know I'm able to send commands no problem, just not sure how to get rid of the extra letter. If anyone could give me some advice that would be great. Thanks for helping.
Byte strings are represented by the b-prefix.
Although you can see the string in output on printing, inherently they are bytes.
To get a normal string out of it, decode function can help.
dataStr.decode("utf-8")
b'data' simply means the data inside quotes has been received in bytes form, as mentioned in other answers also, you have to decode that with decode('utf-8') to get it in string form.
I have updated your program below, to be compatible for v3.7+
from socket import *
isoCmd = ['auto','100','200','300','400','500','640','800']
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
brightness = 50
timelapse = 0
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print ('Waiting for connection')
tcpCliSock,addr = tcpSerSock.accept()
try:
while True:
data = ''
brightness = ' '
data = tcpCliSock.recv(BUFSIZE).decode('utf-8')
print ("Here's data "+data)
if not data:
break
if data in isoCmd:
if data == "auto":
camera.iso = 0
print ('ISO: Auto')
else:
camera.iso = int(data)
print ('ISO: '+ data)
except Exception as e:
print(e)

Read incorrect data from UART in BananaPi

I am using a BananaPi to read UART data coming from a device. I know for sure what is the data generated by the device, it's the same 40 byte sequence sent in a loop, I know for sure because I mesure it with an oscilloscope. The data sent looks like(on the oscilloscope): 6A000496ED47.... 6A000496ED47....
I want to read this data in the BananaPi and I write a python script that looks like:
import serial
import time
if __name__ == '__main__':
connection = serial.Serial()
connection.port = "/dev/ttyS2"
connection.baudrate = 4000000
connection.timeout = 1
try:
connection.open()
print("serial port open")
idx = 0
while(idx < 10):
data = connection.read(size=40)
newData = data.encode('hex')
print newData
idx += 1
connection.close()
except:
print("Opening serial error")
The output is:
b777fbdc63e76....
So I get different sets of 40 bytes data on every of the 10 while loops.
Any ideea what might be wrong?
The serial setup is the same as in the oscilloscope meaning the baudrate is 4000000

Communicating with air-conditioner controller using pyserial

I am trying to the first time to send and receive information through serial port. The manual for the device with which I am trying to talk can be found here. I am trying for a start to send a set of hexadecimals to ask about the condition of the system and my purpose is to ask in real time about the temperature and store it. Until now my code is this:
import serial
import time
#import serial.tools.list_ports
#ports = list(serial.tools.list_ports.comports())
#for p in ports:
# print p
ser = serial.Serial(port= '/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_EVEN,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS, timeout=0, xonxoff=1, rtscts=1, dsrdtr=1)
command = "\x10\xFF\x29\x2C\x16"
command = command.decode("hex")
ser.write(command)
print command
#time.sleep(10)
ReceivedData = "\n nothing"
while ser.inWaiting() > 0:
ReceivedData = ser.read()
print ReceivedData
The problem is that I cannot get any response.
EDIT:
So I solved the communication problem. It turned out I was using an extension cable so the T and R channels were not correctly connected. Now The response that I receive is "\x00\x10\xFF\x29\x2C\x16" which is the same that I put in only with a \x00 in the front. Does this mean it is an error message? How do I calculate the 4th bit? Until now I am using an example from the manual.
dont use command = command.decode("hex")
just
command = "\x10\xFF\x29\x2C\x16"
ser.write(command)
should work i am sure it expects bytes like this
to put it differently
START_BYTE = "\x10"
ADDR_BYTE = "\xff"
FN_BYTE = "\x29"
CS_BYTE = "\x2C" # We assume you have calculated this right
END_BYTE = "\x16"
msg = START_BYTE+ADDR_BYTE+FN_BYTE+CS_BYTE+END_BYTE
ser.write(msg)
you can abstract this out since start and end and address are always the same
def send_fn(ser,FN_CMD):
START_BYTE = "\x10"
ADDR_BYTE = "\xff"
END_BYTE = "\x16"
CS_BYTE = chr((ord(ADDR_BYTE) + ord(FN_CMD))&0xFF)
msg = START_BYTE+ADDR_BYTE+FN_CMD+CS_BYTE+END_BYTE
ser.write(msg)

Finding string Python Arduino

I have a little script in Python which I am brand new to. I want to check if a certain word appears in ser.readline(). The syntax for the If statement is not right and I am not sure how to lay this out so it continuously reads the serial for the word "sound". I've attached an output image below so you can see how it is printing. I'd like to trigger an MP3 as it finds the word "sound" but as of yet I haven't even managed to get it to print a confirmation saying its found the word.
import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)
while 1:
try:
print (ser.readline())
time.sleep(1)
**if "sound" in ser.readline():
print("foundsound")**
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
You may be reading from the port more often than you intend to. I would call ser.readline() just once per iteration of your main loop:
while True:
try:
data = ser.readline().decode("utf-8") # Read the data
if data == '': continue # skip empty data
print(data) # Display what was read
time.sleep(1)
if "sound" in data:
print('Found "sound"!')
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
can you try:
import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)
while 1:
try:
line = ser.readline()
print line
time.sleep(1)
**if "sound" in line:
print("foundsound")**
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)

pyserial readline() : SerialException

I'm writing a code used to send order to an avr. I send several information but between each write, I have to wait for an answer (I have to wait for the robot to reach a point on the coordinate system). As I read in the documentation, readline() should at least read until the timeout but as soon as I send the first coordinate, the readline() automatically return :
SerialException: device reports readiness to read but returned no data (device disconnected?)
When I put a sleep() between each write() in the for loop, everything works fine. I tried to use inWaiting() but it still does not work. Here is an example of how I used it:
for i in chemin_python:
self.serieInstance.ecrire("goto\n" + str(float(i.x)) + '\n' + str(float(-i.y)) + '\n')
while self.serieInstance.inWaiting():
pass
lu = self.serieInstance.readline()
lu = lu.split("\r\n")[0]
reponse = self.serieInstance.file_attente.get(lu)
if reponse != "FIN_GOTO":
log.logger.debug("Erreur asservissement (goto) : " + reponse)
Here an snipet how to use serial in python
s.write(command);
st = ''
initTime = time.time()
while True:
st += s.readline()
if timeout and (time.time() - initTime > t) : return TIMEOUT
if st != ERROR: return OK
else: return ERROR
This method allows you to separately control the timeout for gathering all the data for each line, and a different timeout for waiting on additional lines.
def serial_com(self, cmd):
'''Serial communications: send a command; get a response'''
# open serial port
try:
serial_port = serial.Serial(com_port, baudrate=115200, timeout=1)
except serial.SerialException as e:
print("could not open serial port '{}': {}".format(com_port, e))
# write to serial port
cmd += '\r'
serial_port.write(cmd.encode('utf-8'))
# read response from serial port
lines = []
while True:
line = serial_port.readline()
lines.append(line.decode('utf-8').rstrip())
# wait for new data after each line
timeout = time.time() + 0.1
while not serial_port.inWaiting() and timeout > time.time():
pass
if not serial_port.inWaiting():
break
#close the serial port
serial_port.close()
return lines

Categories