在 RASPBERRY PI 3B+ 中使用 PYTHON GUI 运行时停止步进电机(相同按钮启动和停止)时出现问题

问题描述 投票:0回答:2

我使用

gui
Python 3 中的相同按钮创建了一个程序来启动和停止步进电机。电机已启动但无法停止。我使用 Raspberry Pi 3 B+ 和 TB6600 驱动程序来控制该电机。我设置的范围(800)意味着360度旋转800步。 帮我随时停止电机,在 800 步之间旋转

这是我的代码

import tkinter as tk
from time import sleep
import RPi.GPIO as GPIO
from threading import Thread

DIR =16
STEP =20
CW =1
CCW =0

GPIO.setmode(GPIO.BCM)
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(STEP, GPIO.OUT)
GPIO.output(DIR,CW)

win=tk.Tk()
win.title("HELLO")
win.geometry("300x400")

def start1():
    global running1
    stop1()
    btn1.config(text="Stop upward", command=stop1)
    running1 = True
    info_label["text"] = "Starting..."

    thread1 = Thread(target=run1, daemon=True)
    thread1.start()

def run1():
    DIR =16
    STEP =20
    CW =1
    CCW =0
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(DIR, GPIO.OUT)
    GPIO.setup(STEP, GPIO.OUT)
    sleep(1)
    GPIO.output(DIR,CW)
    for x in range(int(800)):
        GPIO.output(STEP,GPIO.HIGH)
        sleep(.0050)
        GPIO.output(STEP,GPIO.LOW)
        sleep(.0050)
    print('hi')

def stop1():
    global running1
    running1 = False
    info_label["text"] = "Stopped"
    btn1.config(text="Start upward", command=start1)

running1=False
info_label = tk.Label(win,text="stepper1 ",bg= "yellow")

btn1 = tk.Button(win, text="Start upward",height="5",width="10",bg="slateblue1", command=start1)
btn1.grid(row=0,column=0)

win.mainloop()
python python-3.x user-interface raspberry-pi3
2个回答
0
投票

您可以在 Python 中的线程中使用事件作为信号。

以事件作为参数启动线程:

stop_event = threading.Event()
threading.Thread(target=run1, args=[stop_event]).start()

run1 需要事件作为参数:

def run1(event):

要停止线程,请检查 for 循环:

for x in range(int(800)):
    if event.is_set():
        break
    GPIO.output(STEP,GPIO.HIGH)
    …

发送您刚刚调用的事件

stop_event.set()

有关更多信息,请参阅此处:https://docs.python.org/3/library/threading.html


0
投票

你的 run 方法对线程外发生的任何事情都是盲目的。 出去。 我为 RPi、python3 和步进电机开发了一个库。能够在多线程和多进程上发送信号(对于多个电机)。可能想看看以下类以获取有关进程间/线程通信的示例:

BloquingQueueWorker 双极步进电机驱动器 事件调度器

该库还在加速策略方面做了大量工作,并对电机进行基准测试以发挥最大作用。

https://github.com/juanmf/StepperMotors/

© www.soinside.com 2019 - 2024. All rights reserved.