Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import RPi.GPIO as GPIO
channels = [
{'label': 'LEFT_MOTOR_POWER', 'pin': 11},
{'label': 'LEFT_MOTOR_FORWARD', 'pin': 13},
{'label': 'LEFT_MOTOR_BACKWARD', 'pin': 15},
{'label': 'RIGHT_MOTOR_POWER', 'pin': 23},
{'label': 'RIGHT_MOTOR_FORWARD', 'pin': 21},
{'label': 'RIGHT_MOTOR_BACKWARD', 'pin': 19},
]
class Car:
def __init__(self, channels=channels):
GPIO.setmode(GPIO.BOARD)
GPIO.setup([i['pin'] for i in channels], GPIO.OUT, initial=GPIO.LOW)
self.channels = channels
self.state = [False for i in channels]
def reset(self):
self.state = [False for i in channels]
def getIndexFromLabel(self, label):
for i, channel in enumerate(self.channels):
if channel['label'] == label:
return i
return None
def commit(self):
GPIO.output([i['pin'] for i in channels], self.state)
def enableByLabel(self, labels):
for label in labels:
self.state[self.getIndexFromLabel(label)] = True
def forward(self):
self.reset()
self.enableByLabel([
'LEFT_MOTOR_POWER',
'LEFT_MOTOR_FORWARD',
'RIGHT_MOTOR_POWER',
'RIGHT_MOTOR_FORWARD',
])
self.commit()
def backward(self):
self.reset()
self.enableByLabel([
'LEFT_MOTOR_POWER',
'LEFT_MOTOR_BACKWARD',
'RIGHT_MOTOR_POWER',
'RIGHT_MOTOR_BACKWARD',
])
self.commit()
def back(self):
self.backward()
def right(self):
self.reset()
self.enableByLabel([
'LEFT_MOTOR_POWER',
# 'LEFT_MOTOR_FORWARD',
'RIGHT_MOTOR_POWER',
'RIGHT_MOTOR_BACKWARD',
])
self.commit()
def left(self):
self.reset()
self.enableByLabel([
'LEFT_MOTOR_POWER',
'LEFT_MOTOR_BACKWARD',
'RIGHT_MOTOR_POWER',
# 'RIGHT_MOTOR_FORWARD',
])
self.commit()
def stop(self):
self.reset()
self.commit()
def cease(self):
self.stop()
def close(self):
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.