a bytes-like object is required, not 'str' error question.

Asked 2 years ago, Updated 2 years ago, 76 views

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np
import serial #Import Serial Library

import time
from time import sleep

arduinoSerialData = serial.Serial('COM6',115200) #Create Serial port object called arduinoSerialData
size_of_the_matrix = 5

x, y = np.meshgrid(np.linspace(0,5,6), np.linspace(0,5,6)) #each axis is from 0 to 3 devided in 4 sections

distances_matrix = np.zeros((size_of_the_matrix,size_of_the_matrix))

fig = plt.figure(figsize=None,facecolor='white')

ax2 = plt.subplot()
quad1 = ax2.pcolormesh(x,y,distances_matrix,vmin=0,vmax=3000,shading='flat')
bar = fig.colorbar(quad1, ax=ax2)
bar.set_label("Ranges in each ROI (mm)")
ax2.set_xlabel('X')
ax2.set_ylabel('Y')

def init():
    quad1.set_array([])
    return quad1

def animate(iter):
    global distances_matrix
    if (arduinoSerialData.inWaiting()>0): #Check if data is on the serial port
        data_receving_from_arduino_as_string= arduinoSerialData.readline()
        distances_in_string = data_receving_from_arduino_as_string.split(',') #Convering the data                                     received from the arduino from string to a float
        distances_in_string.pop()
        distances = [float(i) for i in distances_in_string]

        if(len(distances)==size_of_the_matrix*size_of_the_matrix):         
          distances_matrix = np.reshape(distances, (size_of_the_matrix, size_of_the_matrix))

          b = distances_matrix[:,0:1]
          #print b
          a = distances_matrix [:,1:5]
          #print a
          c = np.concatenate((a,b), axis =1) 

          distances_matrix = np.flipud(c)
          #distances_matrix = c

    #print distances_matrix
    quad1.set_array(distances_matrix.ravel())

anim = animation.FuncAnimation(fig,animate ,interval=100,blit=False,repeat=False)
plt.show()

such as titles in the ikodeu distances are [) (I float for I in distances in _ string] part of an error occurred. In other can not be resolved in the same way and distances : [float decode ()). (I for I in distances in _ string]. What's wrong?

The full text of the error message is as follows!

PS C:\Users\hjj96> & python "c:/Users/hjj96/Desktop/Lidar-using-VL53L1X-            master/Files_for_demo/Files for demo/Read_and_plot_2d_map.py"
   Traceback (most recent call last):
  File "C:\Users\hjj96\anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 1216, in             _on_timer
       ret = func(*args, **kwargs)
  File "C:\Users\hjj96\anaconda3\lib\site-packages\matplotlib\animation.py", line 1477, in _step
        still_going = super()._step(*args)
  File "C:\Users\hjj96\anaconda3\lib\site-packages\matplotlib\animation.py", line 1189, in _step
    self._dra    w_next_frame(framedata, self._blit)
  File "C:\Users\hjj96\anaconda3\lib\site-packages\matplotlib\animation.py", line 1208, in     _draw_next_frame
    self._draw_frame(framedata)
  File "C:\Users\hjj96\anaconda3\lib\site-packages\matplotlib\animation.py", line 1776, in     _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
  File "c:/Users/hjj96/Desktop/Lidar-using-VL53L1X-master/Files_for_demo/Files for     demo/Read_and_plot_2d_map.py", line 44, in animate
    distances_in_string = data_receving_from_arduino_as_string.split(',') #Convering the data     received from the arduino from string to a float
TypeError: a bytes-like object is required, not 'str'

python arduino

2022-09-20 17:05

1 Answers

If a bytes-like object is required, not 'str' occurs in data_receasing_from_arduino_as_string(';'), I think data_receiving_from_arduino_as_string is not a string, but a byte-array.

>>> s = b'abcde'
>>> s.split('c')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    s.split('c')
TypeError: a bytes-like object is required, not 'str'

You can reproduce the same error like this.

To fix this, an error occurred while trying to split the byte array into a string (';'), so if you just split it into b'',' there won't be an error.

>>> s = b'abcde'
>>> s.split('c')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    s.split('c')
TypeError: a bytes-like object is required, not 'str'
>>> s.split(b'c')
[b'ab', b'de']


2022-09-20 17:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.