I use pySerialTTL for reading a stream of bytes. To read two bytes:
CheckSumByte = [ b for b in ser.read(2)]
print( CheckSumByte)
print( type(CheckSumByte))
print( str(len(CheckSumByte)))
print( CheckSumByte[0])
Conclusion:
[202, 87]
<class 'list'>
2
IndexError: list index out of range
I cannot access elements CheckSumByteby index (0 or 1). What's wrong?
Here is my code:
while(ReadBufferCount < 1000):
time.sleep(0.00002)
InputBuffer = ser.inWaiting()
if (InputBuffer > 0):
FirstByte = ser.read(1)
if ord(FirstByte) == 0xFA:
while ser.inWaiting() < 21: pass
IndexByte = ser.read(1)
SpeedByte = [ b for b in ser.read(2)]
DataByte0 = [ b for b in ser.read(4)]
DataByte1 = [ b for b in ser.read(4)]
DataByte2 = [ b for b in ser.read(4)]
DataByte3 = [ b for b in ser.read(4)]
CheckSumByte = [ b for b in ser.read(2)]
print( CheckSumByte[0])
Traceback (most recent call last):
File "<ipython-input-6-5233b0a578b1>", line 1, in <module>
runfile('C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py', wdir='C:/Users/Blair/Documents/Python/Neato XV-11 Lidar')
File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 682, in runfile
execfile(filename, namespace)
File "C:\Program Files (x86)\WinPython-32bit-3.4.3.3\python-3.4.3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/Blair/Documents/Python/Neato XV-11 Lidar/Serial9.py", line 88, in <module>
print( CheckSumByte[0]) #Out of Range??
IndexError: list index out of range
Kenny: Thanks. Even simpler for two bytes:
CheckSumByte.append(ser.read(1))
CheckSumByte.append(ser.read(1))
It works correctly, but inconveniently. Elements are type bytes. How to add items to a list using list comprehension? I would like to avoid the append function because it is slow.
I notice that this does not work when the CheckSumByte elements are integer. In Python 3's understanding, does it need a special format for adding bytes to bytes (not for converting to an integer)?