I'd like to test the content of a variable containing a byte in a way like this:
line = []
while True:
for c in self.ser.read(): # read() from pySerial
line.append(c)
if c == binascii.unhexlify('0A').decode('utf8'):
print("Line: " + line)
line = []
break
But this does not work... I'd like also to test, if a byte is empty: In this case
print(self.ser.read())
prints: b'' (with two single quotes)
I do not until now succeed to test this
if self.ser.read() == b''
or what ever always shows a syntax error...
I know, very basic, but I don't get it...
In the case of a byte (an 8-bit binary value, or Byte, the object model of a byte) you need to determine beforehand in the design stage what an “empty” byte value is, if that is possible in your program. It could be 0 or -1 or 0xFF , any 8-bit value that symbolizes “empty” or “nothing”.
Since all three arguments are optional, we can pass an empty string to generate an empty byte array (Byte array of size 0). Depending on the type of the source parameter, an appropriate byte array will be initialized. If source is a String, Python bytes() will convert the string to bytes using str. encode() .
Only object references can be null; bytes can be zero, though, as you obviously know, and that's what you meant. In your code snippet, the loop is completely unnecessary; when you allocate the array, all the elements are guaranteed to be zero already.
bytes() takes three optional parameters: source (Optional) - source to initialize the array of bytes. encoding (Optional) - if the source is a string, the encoding of the string. errors (Optional) - if the source is a string, the action to take when the encoding conversion fails (Read more: String encoding)
If you want to verify the contents of your variable or string which you want to read from pySerial, use the repr()
function, something like:
import serial
import repr as reprlib
from binascii import unhexlify
self.ser = serial.Serial(self.port_name, self.baudrate, self.bytesize, self.parity, self.stopbits, self.timeout, self.xonxoff, self.rtscts)
line = []
while 1:
for c in self.ser.read(): # read() from pySerial
line.append(c)
if if c == b'\x0A':
print("Line: " + line)
print repr(unhexlify(''.join('0A'.split())).decode('utf8'))
line = []
break
Thank you for your help. The first part of the question was answerd by @sisanared:
if self.ser.read():
does the test for an empty byte
The second part of the question (the end-of-line with the hex-value 0A) stil doesn't work, but I think it is whise to close this question since the answer to the title is given.
Thank you all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With