Я пытаюсь создать функцию для получения компонентов гироскопа X, Y, Z от датчика.
Функция следующая:
def bimu_get_gyroscope_raw():
#ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=15)
ser = serial.Serial('/dev/tty.usbserial-00002014', 115200, timeout=15)
ser_io = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1),
newline = '\r',
line_buffering = True)
try:
ser.isOpen()
print('serial is open')
except:
print('error_1')
exit()
#--------------------
i = 0
gyro_dict = dict()
if (ser.isOpen()):
ser.flushInput()
# write the function to get
while (i==0):
try:
print('serial is open_1')
line = ser_io.readline()
print('serial is open_2')
print(line)
except serial.SerialException as err:
print("Error ocurred while reading data: {}".format(err))
if not line.endswith('\r'):
print("Attempt to read from serial port timed out ... Exiting.")
break # terminate the loop and let the program exit
if line.startswith('S,'):
i += 1
line = line.split(',')
print(line)
if len(line)==12:
gyro_dict = {'x':float(line[1]), 'y': float(line[2]), 'z': float(line[3]) }
else:
print('Cannot open serial port')
return gyro_dict
Я получаю следующий вывод :
raw = bimu_get_gyroscope_raw()
print(raw)
serial is open
serial is open_1
-43,-122,-2833,83,65
serial is open_2
serial is open_1
S,2,0,0,-20,19,1014,-146,184,-158,168,99
serial is open_2
['S', '2', '0', '0', '-20', '19', '1014', '-146', '184', '-158', '168', '99\r']
{'z': 0.0, 'y': 0.0, 'x': 2.0}
Проблема, с которой я сталкиваюсь, заключается в том, что между первым вызовом линии line = ser_io.readline()
и ручным хронометром для записи на экране требуется около 2,25 с serial is open_2
.
Если функция должна вызывать снова ser_io.readline()
нет задержки, и линии serial is open_1
и serial is open_2
появляются почти одновременно.
Я думаю, что первый вызов readline()
что-то внутренне делает с портом или из-за того, что буфер данных, который уже выполнен, заставляет последовательные вызовы readline()
выполняться намного быстрее.
Есть ли способ решить эту проблему и заставить функцию работать постоянно.
РЕДАКТИРОВАТЬ
Я проверил время с модулем time
python и изменил часть readline, например:
while (i<=5):
try:
print('before readline')
start_time = time.time()
line = ser_io.readline()
#print(line)
print("--- %s seconds ---" % (time.time() - start_time))
#print(line)
print('after readline')
except serial.SerialException as err:
print("Error ocurred while reading data: {}".format(err))
if not line.endswith('\r'):
print("Attempt to read from serial port timed out ... Exiting.")
break # terminate the loop and let the program exit
if line.startswith('S,'):
i += 1
line = line.split(',')
print(line)
if len(line)==12:
gyro_dict = {'x':float(line[1]), 'y': float(line[2]), 'z': float(line[3]) }
со следующим результат:
serial is open
before readline
--- 2.1859400272369385 seconds ---
after readline
before readline
--- 5.9604644775390625e-06 seconds ---
after readline
['S', '0', '0', '0', '380', '0', '-902', '-497', '-228', '200', '63', '103\r']
before readline
--- 2.86102294921875e-06 seconds ---
after readline
before readline
--- 3.814697265625e-06 seconds ---
after readline
['S', '-1', '0', '1', '375', '-8', '-918', '-497', '-223', '194', '64', '108\r']
before readline
--- 3.0994415283203125e-06 seconds ---
after readline
['S', '1', '0', '2', '380', '-10', '-909', '-500', '-223', '200', '65', '113\r']
before readline
--- 2.1457672119140625e-06 seconds ---
after readline
before readline
--- 1.9073486328125e-06 seconds ---
after readline
['S', '0', '0', '0', '379', '-1', '-914', '-500', '-220', '197', '66', '69\r']
before readline
--- 2.1457672119140625e-06 seconds ---
after readline
['S', '0', '0', '-1', '374', '-5', '-902', '-500', '-225', '1\r']
before readline
--- 3.0994415283203125e-06 seconds ---
after readline
['S', '1', '1', '1', '376', '-2', '-915', '-500', '-223', '192', '37', '75\r']
Функция занимает более двух o секунд первой итерации, остальные итерации очень быстрые.