我有一个程序,它应该发送几个数据点通过串行连接到一个arduino,这将控制一些电机移动。我可以单独发送控制信号,也可以通过txt文件发送,该文件将重复运行,直到文件完成。在运行txt文件时,我希望能够像暂停或停止按钮一样退出循环。我认为最好的办法是通过一个线程,我可以关闭。我从来没有做过任何线程之前,我的初步尝试没有工作。下面是发送文件数据的函数。你知道吗
def send_file():
# Global vars
global moto1pos
global motor2pos
# Set Ready value
global isready
# Get File location
program_file_name = file_list.get('active')
file_path = "/home/evan/Documents/bar_text_files/"
program_file = Path(file_path + program_file_name)
file = open(program_file)
pos1 = []
pos2 = []
speed1 = []
speed2 = []
accel1 = []
accel2 = []
for each in file:
vals = each.split()
pos1.append(int(vals[0]))
pos2.append(int(vals[1]))
speed1.append(int(vals[2]))
speed2.append(int(vals[3]))
accel1.append(int(vals[4]))
accel2.append(int(vals[5]))
# Send file values
try:
while isready == 1:
for i in range(len(pos1)):
print("Step: " + str(i+1))
data = struct.pack("!llhhhh", pos1[i], pos2[i], speed1[i], speed2[i], accel1[i], accel2[i])
ser.write(data)
try:
pos1time = abs(pos1[i]/speed1[i])
except:
pos1time = 0
try:
pos2time = abs(pos2[i]/speed2[i])
except:
pos2time = 0
time_array = (pos1time, pos2time)
time.sleep(max(time_array))
motor1pos = ser.readline()
motor2pos = ser.readline()
if i < (len(pos1)-1):
isready = ord(ser.read(1))
else:
isready = 0
except:
print("Error: data not sent. Check serial port is open")
下面是我希望sendfile命令从中工作的线程命令。你知道吗
def thread():
try:
global isready
isready = 1
t = threading.Thread(name='sending_data', target=command)
t.start()
except:
print("Threading Error: you don't know what you are doing")
这是我想要终止线程的停止函数:
def stop():
try:
global isready
isready = 0
t.kill()
except:
print("Error: thread wasn't killed")
我知道你不应该杀死一个线程,但数据不是很重要。更重要的是在有东西坏之前把马达停下来。你知道吗
tkinter中的按钮是:
run_file_butt = tk.Button(master = file_frame, text = "Run File", command = thread)
当我点击按钮,程序运行,但停止功能不停止运动。你知道吗
我的答案很简单,因为我对线程的简单理解和使用线程的独特环境。我没有按我所希望的方式终止线程,而是在send\u file函数的发送行中添加了另一个条件语句。你知道吗
我已经将stop()函数更新为:
我不太清楚它是如何工作的,但它比@stovefl提到的要简单得多。你知道吗
有了这段代码,因为函数基本上只是在休眠,所以它可以运行,但不会发送任何新信息,然后在下一次迭代后将执行.join()。你知道吗
没有所谓的
.kill(...
。开始使你的
def send_file(...
成为一个Thread object
,它正在等待你的命令。你知道吗你的
tk.Button
应该是这样的:相关问题 更多 >
编程相关推荐