Jun-03-2020, 04:02 PM
Hi,
I am new to python. I have a device. This device gives serial data. When I read the serial data using python I can see that data is something like below.
\000026hi
\000026hi
there are lot space coming with the serial data. I can not modify the data from the serial device.
In the python script I need to eliminate the spaces and print only the data and compare that data with our data and print if matches.
here is my code. This code prints the data from serial device to the file using python.
here I took a variable called scan1 and put my data. If the serial data matches to the variable scan1 then print the data with good read message.
The output is
It is printing
\000026hi
\000026hi
the if statement is always false. I knew it is due to the spaces. Can some one help me with eliminating the spaces and printing only the data without spaces and compare with my variable. Thank you.
I am new to python. I have a device. This device gives serial data. When I read the serial data using python I can see that data is something like below.
\000026hi
\000026hi
there are lot space coming with the serial data. I can not modify the data from the serial device.
In the python script I need to eliminate the spaces and print only the data and compare that data with our data and print if matches.
here is my code. This code prints the data from serial device to the file using python.
here I took a variable called scan1 and put my data. If the serial data matches to the variable scan1 then print the data with good read message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
from __future__ import print_function import serial, time, io, datetime from serial import Serial import time #ser = serial.Serial('/dev/ttyUSB0',115200) addr = "COM10" ## serial port to read data from baud = 115200 ## baud rate for instrument ser = serial.Serial( port = addr,\ baudrate = baud,\ parity = serial.PARITY_NONE,\ stopbits = serial.STOPBITS_ONE,\ bytesize = serial.EIGHTBITS,\ timeout = 0 ) print ( "Connected to: " + ser.portstr) filename = "Scanner_Data.txt" f = open ( "Scanner_Data.txt" , "a" ) scan1 = "000026hi" while True : with open ( "Scanner_Data.txt" , "a" ) as f: s = ser.readline() line = s.decode( 'utf-8' ).replace( '\r\n' , '') time.sleep( 1 ) print (line) if (line) = = scan1: print ( "Good Read" ) f.write(line + "Good Read" + "\r\n" ) f.close() f.write(line + "\r\n" ) f.close() |
It is printing
\000026hi
\000026hi
the if statement is always false. I knew it is due to the spaces. Can some one help me with eliminating the spaces and printing only the data without spaces and compare with my variable. Thank you.