问题遇到的现象
用的是虚拟串口,xcom的com2发送几次,电脑com1接收几次字符串(如1 1 1 1 1 1 1 0.3 0.7 0.2 0.1)以后报错,
这是我的代码
import serial
import threading
from time import sleep
def recv(serial):
while True:
data = serial.read_all().decode() # str
if data == '':
continue
else:
break
return data
def COM1():
if __name__ == '__main__':
serial1 = serial.Serial('COM1', 115220, timeout=0.5)
if serial1.isOpen():
print("COM1 open success")
else:
print("COM1 open failed")
while True:
data1 = recv(serial1)
DATA1=data1.split()
KG01=int(DATA1[0])
KG02=int(DATA1[1])
KG03=int(DATA1[2])
KG04=int(DATA1[3])
KG05=int(DATA1[4])
KGLL=int(DATA1[5])
KGRR=int(DATA1[6])
X1=float(DATA1[7])
Y1=float(DATA1[8])
X2=float(DATA1[9])
Y2=float(DATA1[10])
Z11=float()
Y11=float()
Z22=float()
Y22=float()
X11=-Y1
if KGLL==0:
Z11=-X1
Y11=0
if KGLL==1:
Y11=-X1
Z11=0
ZD=[X11,Y11,Z11]
print(ZD)
X22=X1
if KGRR==0:
Z22=0
Y22=Y2
if KGRR==1:
Y22=0
Z22=-Y2
YD=[X22,Y22,Z22]
print(YD)
def COM3():
if __name__ == '__main__':
serial3 = serial.Serial('COM3',115200 , timeout=0.5)
if serial3.isOpen():
print("COM3 open success")
else:
print("COM3 open failed")
while True:
data3 = recv(serial3)
CR=data3.split()
print(CR[0])
print(CR[1])# str
thread1 = threading.Thread(name='t1',target= COM1)
thread2 = threading.Thread(name='t2',target= COM3)
thread1.start()#启动线程1
thread2.start()#启动线程2
这边是报错
COM1 open success
COM3 open success
[-0.7, -0.3, 0]
[0.3, 0, -0.1]
[-0.7, -0.3, 0]
[0.3, 0, -0.1]
Exception in thread t1:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\ProgramData\Anaconda3\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\lrc\AppData\Local\Temp/ipykernel_12376/1791913573.py", line 35, in COM1
IndexError: list index out of range