简体   繁体   中英

Problem to stop a STEPPER MOTOR (same button start and stop) while running by using PYTHON GUI IN RASPBERRY PI 3B+

I create a program to start and stop a stepper motor by using same button in gui Python 3. The motor is start but unable to stop. I am using Raspberry Pi 3 B+ and TB6600 driver to control this motor. I set the range (800) means 800 steps in 360 degree revolution. help me to stop the motor whenever I want, revolving in between 800 steps

here is my code

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()

You can use Events for signals in threads in Python.

To start your thread with the event as argument:

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

The run1 needs the event as argument:

def run1(event):

To stop the thread make a check in your for loop:

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

To send the event you just call

stop_event.set()

For more information see here: https://docs.python.org/3/library/threading.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM