-
Notifications
You must be signed in to change notification settings - Fork 0
/
motor.py
81 lines (59 loc) · 1.93 KB
/
motor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""Motor drive utilities.
See Adafruit lesson 9 for circuit diagram.
Copyright (C) 2015 Tom Oakley
MIT licence
"""
import logging
import time
import RPi.GPIO as GPIO
class Motor():
def __init__(self):
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
self._in1_pin = 4
self._in2_pin = 17
self._pwm_pin = 18
GPIO.setup(self._in1_pin, GPIO.OUT)
GPIO.setup(self._in2_pin, GPIO.OUT)
GPIO.setup(self._pwm_pin, GPIO.OUT)
# Set up PWM
# pwm = GPIO.PWM(_pwm_pin, 20000)
# pwm.start(100)
self._drive_count = 0
def __enter__(self):
"""Enter context manager to use with `with` statement."""
return self
def __exit__(self, exc_type, exc_value, exc_tb):
"""Exit context manager to use with `with` statement."""
GPIO.cleanup()
def drive(self, duty, time_=0.5):
"""Drive the motor.
duty is:
100 for clockwise
-100 for counter clockwise
0 for stop
time_ is the time in seconds. Set to negative for no timeout
"""
assert -100 <= duty <= 100
if duty == 0:
# Stop the motor
GPIO.output(self._in1_pin, False)
GPIO.output(self._in2_pin, False)
GPIO.output(self._pwm_pin, False)
return
self._drive_count += 1
fmt = 'Drive #{} at {} duty for {} s'
logging.debug(fmt.format(self._drive_count, duty, time_))
if duty > 0:
GPIO.output(self._in1_pin, True)
GPIO.output(self._in2_pin, False)
GPIO.output(self._pwm_pin, True)
else:
GPIO.output(self._in1_pin, False)
GPIO.output(self._in2_pin, True)
GPIO.output(self._pwm_pin, True)
if time_ >= 0:
# Sleep whilst the motor runs
time.sleep(time_)
# Stop the motor
self.drive(0)