Jul-24-2020, 04:53 AM
Hello,
I'm writing a program to control a stepper motor using keyboard presses. The problem I'm having is that once I press a key to start the motor turning in one direction, I don't know how to interrupt the movement to either stop it or turn it in a different direction. I tried adding an if statement within one of the for loops but that did not work.
I'm writing a program to control a stepper motor using keyboard presses. The problem I'm having is that once I press a key to start the motor turning in one direction, I don't know how to interrupt the movement to either stop it or turn it in a different direction. I tried adding an if statement within one of the for loops but that did not work.
import curses import time import RPi.GPIO as GPIO screen = curses.initscr() curses.noecho() curses.cbreak() screen.keypad(True) GPIO.setmode(GPIO.BOARD) ControlPin = [7,11,13,15] for pin in ControlPin: GPIO.setup (pin, GPIO.OUT) GPIO.output (pin, 0) seq2 = [[1,0,0,0], [1,0,0,0], [0,1,0,0], [0,1,0,0], [0,0,1,0], [0,0,1,0], [0,0,0,1], [0,0,0,1], [1,0,0,0],] seq3 = [[1,0,0,0], [0,0,0,1], [0,0,0,1], [0,0,1,0], [0,0,1,0], [0,1,0,0], [0,1,0,0], [1,0,0,0], [1,0,0,0],] try: while True: char = screen.getch() if char == ord('q'): break # right turning elif char == curses.KEY_RIGHT: for i in range(512): print("right") if char == curses.KEY_LEFT or char == 10: break for halfstep in range(9): for pin in range(4): GPIO.output(ControlPin[pin], seq2[halfstep][pin]) time.sleep(0.001) # left turning elif char == curses.KEY_LEFT: for i in range(512): print("left") if char == curses.KEY_RIGHT or char == 10: break for halfstep in range(9): for pin in range(4): GPIO.output(ControlPin[pin], seq3[halfstep][pin]) time.sleep(0.001) # stop elif char == 10: for i in range(512): print("stop") if char == curses.KEY_LEFT or char == curses.KEY_RIGHT: break for halfstep in range(9): for pin in range(4): GPIO.output(ControlPin[pin], seq2[halfstep][pin]) time.sleep(0.001) GPIO.cleanup() except: GPIO.cleanup() print("error")