所以我有两个正在运行的线程,但是我似乎无法停止使用KeyboardInterrupt。函数emg()和gyro()应该从2个不同的设备收集连续的传入数据,并且我使用了线程,因此我可以同时收集数据。我对其进行了测试,并且能够收集数据,但是无法通过KeyboardInterrupt停止它。有没有更好的方法可以停止它,还是应该以其他方式编码KeyboardInterrupt?下面是代码的一部分。对不起,缩进很乱!
def emg():
print "Packet Type,\tTimestamp, \tChip1 Status, \tChip1 Channel 1,2 (mv), \tChip2 Status, \tChip2 Channel 1,2 (mV)"
try:
while True:
while numbytes < framesize:
ddata += ser.read(framesize)
numbytes = len(ddata)
data = ddata[0:framesize]
ddata = ddata[framesize:]
numbytes = len(ddata)
(packettype,) = struct.unpack('B', data[0:1])
# (timestamp, c1status) = struct.unpack('HB', data[1:4])
(ts0, ts1, ts2, c1status) = struct.unpack('BBBB', data[1:5])
timestamp = ts0 + ts1*256 + ts2*65536
# 24-bit signed values MSB values are tricky, as struct only supports 16-bit or 32-bit
# pad with zeroes at LSB end and then shift the result
if exgRes_24bit:
# chip 1
c1ch1 = struct.unpack('>i', (data[5:8] + '\0'))[0] >> 8
c1ch2 = struct.unpack('>i', (data[8:11] + '\0'))[0] >> 8
# status byte
(c2status,) = struct.unpack('B', data[11:12])
# chip 2
c2ch1 = struct.unpack('>i', (data[12:15] + '\0'))[0] >> 8
c2ch2 = struct.unpack('>i', (data[15:framesize] + '\0'))[0] >> 8
else:
# chip 1
c1ch1 = struct.unpack('>h', data[5:7])[0]
c1ch2 = struct.unpack('>h', data[7:9])[0]
# status byte
(c2status,) = struct.unpack('B', data[9:10])
# chip 2
c2ch1 = struct.unpack('>h', data[10:12])[0]
c2ch2 = struct.unpack('>h', data[12:framesize])[0]
# Calibrate exg channels:
c1ch1 *= exgCalFactor
c1ch2 *= exgCalFactor
c2ch1 *= exgCalFactor
c2ch2 *= exgCalFactor
print "0x%02x,\t\t%5d,\t0x%02x,\t\t%2.4f,%2.4f,\t\t%s0x%02x,\t\t%2.4f,%2.4f" % \
(packettype, timestamp, c1status, c1ch1, c1ch2, "\t" if c1ch1>0 else "", c2status, c2ch1, c2ch2)
except KeyboardInterrupt:
#send stop streaming command
ser.write(struct.pack('B', 0x20))
wait_for_ack()
#close serial port
ser.close()
print
`enter code here`print "All done!"
def gyro():
print "Packet Type,Timestamp,Analog AccelX,Analog AccelY,Analog AccelZ,GSR Range,GSR,GyroX,GyroY,GyroZ"
try:
while True:
while numbytes1 < framesize1:
ddata1 += ser1.read(framesize1)
numbytes1 = len(ddata1)
data1 = ddata1[0:framesize1]
ddata1 = ddata1[framesize1:]
numbytes1 = len(ddata1)
(packettype1,) = struct.unpack('B', data1[0:1])
(timestamp0, timestamp1, timestamp2) = struct.unpack('BBB', data1[1:4])
timestamp3 = timestamp0 + timestamp1*256 + timestamp2*65536
(analogacceyx, analogacceyy, analogacceyz, gsr) = struct.unpack('HHHH', data1[4:12])
(gyrox, gyroy, gyroz) = struct.unpack('>hhh', data1[12:framesize1])
gsrrange = (gsr & 0xC000) >> 14
gsr &= 0xFFF
#time.append(timestamp)
#c1.append(gyrox)
#c2.append(gyroy)
#c3.append(gyroz)
print "0x%02x,%5d,\t%4d, %4d, %4d,\t%d, %4d,\t%4d, %4d, %4d" % (packettype1, timestamp3, analogacceyx, analogacceyy, analogacceyz, gsrrange, gsr, gyrox, gyroy, gyroz)
thread1=emg()
thread2=gyro()
thread1.start()
thread2.start()
except KeyboardInterrupt:
print("done")