Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import RPi.GPIO as GPIO
- import time
- from time import sleep
- # global vars
- pwmpinL = 18
- pwmpinR = 13
- directionL = 22
- directionR = 23
- pwmfreq=1000 # set PWM frequency to 10Khz, compatible with slow slew mode on the motor controller
- dc = 25 # percent duty cycle to test with
- GPIO.setmode(GPIO.BCM) # set pin selection mode
- GPIO.setup(pwmpinL, GPIO.OUT) #set left motor's pin to output mode
- GPIO.setup(pwmpinR, GPIO.OUT) #set right motor's pin to output mode
- GPIO.setup(directionL, GPIO.OUT) #set right motor's pin to output mode
- GPIO.setup(directionR, GPIO.OUT) #set right motor's pin to output mode
- pwmL = GPIO.PWM(pwmpinL, pwmfreq)
- pwmR = GPIO.PWM(pwmpinR, pwmfreq)
- #dirL = GPIO.OUT(directionL, 1)
- #dirR = GPIO.OUT(directionR, 1)
- #GPIO.output(pwmpinL, GPIO.LOW)
- # Some simple predefined motor control functions
- def stopmotors():
- global dc
- pwmL.stop()
- pwmR.stop()
- return
- def turnright():
- global dc
- pwmR.stop()
- pwmL.start(dc)
- return
- def turnleft():
- global dc
- pwmL.stop()
- pwmR.start(dc)
- return
- def gostraight():
- global dc
- pwmL.start(dc) #start running left motor at test duty cycle
- pwmR.start(dc) #start running left motor at test duty cycle
- return
- def changespeed(newspeed):
- global dc
- dc=newspeed*25
- return
- # Code to get keypresses
- class _Getch:
- """Gets a single character from standard input. Does not echo to the
- screen."""
- def __init__(self):
- try:
- self.impl = _GetchWindows()
- except ImportError:
- self.impl = _GetchUnix()
- def __call__(self): return self.impl()
- class _GetchUnix:
- def __init__(self):
- import tty, sys
- def __call__(self):
- import sys, tty, termios
- fd = sys.stdin.fileno()
- old_settings = termios.tcgetattr(fd)
- try:
- tty.setraw(sys.stdin.fileno())
- ch = sys.stdin.read(1)
- finally:
- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
- return ch
- class _GetchWindows:
- def __init__(self):
- import msvcrt
- def __call__(self):
- import msvcrt
- return msvcrt.getch()
- print("Use W/A/S/D to move, numbers 1~4 to adjust movement speed. Press C to exit")
- # Keypress polling loop
- while True:
- getch = _Getch()
- if (getch=="w"):
- gostraight()
- if (getch=="a"):
- turnleft()
- if (getch=="d"):
- turnright()
- if (getch=="s"):
- stopmotors()
- if (getch=="1"):
- changespeed(1)
- if (getch=="2"):
- changespeed(2)
- if (getch=="3"):
- changespeed(3)
- if (getch=="4"):
- changespeed(4)
- if (getch=="c"):
- stopmotors()
- break
- sleep(0.05)
- GPIO.cleanup()
Advertisement
Add Comment
Please, Sign In to add comment