Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ev3dev/GyroBalancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import time
from collections import deque
from ev3dev.auto import *
from ev3dev.helper import Tank
from ev3dev.helper import LargeMotorPair


log = logging.getLogger(__name__)
Expand Down Expand Up @@ -63,7 +63,7 @@ def SetDuty(motorDutyFileHandle, duty):
FastWrite(motorDutyFileHandle, duty)


class GyroBalancer(Tank):
class GyroBalancer(LargeMotorPair):
"""
Base class for a robot that stands on two wheels and uses a gyro sensor
to keep its balance.
Expand All @@ -77,7 +77,7 @@ def __init__(self,
gainMotorAngleErrorAccumulated, # For every radian x s of accumulated motor angle, apply this amount of duty cycle
left_motor=OUTPUT_D,
right_motor=OUTPUT_A):
Tank.__init__(self, left_motor, right_motor)
LargeMotorPair.__init__(self, left_motor, right_motor)

# magic numbers
self.gainGyroAngle = gainGyroAngle
Expand Down
317 changes: 270 additions & 47 deletions ev3dev/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import sys
import time
import ev3dev.auto
from collections import OrderedDict
from ev3dev.auto import (RemoteControl, list_motors,
INPUT_1, INPUT_2, INPUT_3, INPUT_4,
OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D)
Expand Down Expand Up @@ -146,6 +147,253 @@ class MediumMotor(ev3dev.auto.MediumMotor, MotorMixin):
pass


class MotorSet(object):
"""
motor_specs is a dictionary such as
{
OUTPUT_A : LargeMotor,
OUTPUT_B : MediumMotor,
}
"""

def __init__(self, motor_specs, desc=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each motor object can tell you what port it's on... why does this need to take a dictionary?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The motor objects haven't been created yet though, we need to know what type of objects to make and which ports each of those objects is associated with.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I read through the rest of the file then forgot to come back and delete this. I've got it now.


for motor_port in motor_specs.keys():
if motor_port not in OUTPUTS:
log.error("%s in an invalid motor, choices are %s" % (motor_port, ', '.join(OUTPUTS)))
sys.exit(1)

self.motors = OrderedDict()
for motor_port in sorted(motor_specs.keys()):
motor_class = motor_specs[motor_port]
self.motors[motor_port] = motor_class(motor_port)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The motor objects are created here


self.desc = desc
self.verify_connected()

def __str__(self):

if self.desc:
return self.desc
else:
return self.__class__.__name__

def verify_connected(self):
for motor in self.motors.values():
if not motor.connected:
log.error("%s: %s is not connected" % (self, motor))
sys.exit(1)

def set_args(self, **kwargs):
motors = kwargs.get('motors', self.motors.values())

for motor in motors:
for key in kwargs:
if key != 'motors':
try:
setattr(motor, key, kwargs[key])
except AttributeError as e:
log.error("%s %s cannot set %s to %s" % (self, motor, key, kwargs[key]))
raise e

def set_polarity(self, polarity, motors=None):
valid_choices = ('normal', 'inversed')
assert polarity in valid_choices,\
"%s is an invalid polarity choice, must be %s" % (polarity, ', '.join(valid_choices))
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.polarity = polarity

def _run_command(self, **kwargs):
motors = kwargs.get('motors', self.motors.values())

for motor in motors:
for key in kwargs:
if key not in ('motors', 'commands'):
log.debug("%s: %s set %s to %s" % (self, motor, key, kwargs[key]))
setattr(motor, key, kwargs[key])

for motor in motors:
motor.command = kwargs['command']
log.debug("%s: %s command %s" % (self, motor, kwargs['command']))

def run_forever(self, **kwargs):
kwargs['command'] = ev3dev.auto.LargeMotor.COMMAND_RUN_FOREVER
self._run_command(**kwargs)

def run_to_abs_pos(self, **kwargs):
kwargs['command'] = ev3dev.auto.LargeMotor.COMMAND_RUN_TO_ABS_POS
self._run_command(**kwargs)

def run_to_rel_pos(self, **kwargs):
kwargs['command'] = ev3dev.auto.LargeMotor.COMMAND_RUN_TO_REL_POS
self._run_command(**kwargs)

def run_timed(self, **kwargs):
kwargs['command'] = ev3dev.auto.LargeMotor.COMMAND_RUN_TIMED
self._run_command(**kwargs)

def run_direct(self, **kwargs):
kwargs['command'] = ev3dev.auto.LargeMotor.COMMAND_RUN_DIRECT
self._run_command(**kwargs)

def reset(self, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.reset()

def stop(self, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.stop()

def _is_state(self, motors, state):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
if state not in motor.state:
return False

return True

@property
def is_running(self, motors=None):
return self._is_state(motors, ev3dev.auto.LargeMotor.STATE_RUNNING)

@property
def is_ramping(self, motors=None):
return self._is_state(motors, ev3dev.auto.LargeMotor.STATE_RAMPING)

@property
def is_holding(self, motors=None):
return self._is_state(motors, ev3dev.auto.LargeMotor.STATE_HOLDING)

@property
def is_overloaded(self, motors=None):
return self._is_state(motors, ev3dev.auto.LargeMotor.STATE_OVERLOADED)

@property
def is_stalled(self):
return self._is_state(motors, ev3dev.auto.LargeMotor.STATE_STALLED)

def wait(self, cond, timeout=None, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.wait(cond, timeout)

def wait_until_not_moving(self, timeout=None, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.wait_until_not_moving(timeout)

def wait_until(self, s, timeout=None, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.wait_until(s, timeout)

def wait_while(self, s, timeout=None, motors=None):
motors = motors if motors is not None else self.motors.values()

for motor in motors:
motor.wait_while(s, timeout)


class MotorPair(MotorSet):

def __init__(self, motor_specs, desc=None):
MotorSet.__init__(self, motor_specs, desc)
(self.left_motor, self.right_motor) = self.motors.values()
self.max_speed = self.left_motor.max_speed

def set_speed_steering(self, direction, speed_outer_motor=100):
"""
Set the speed_sp for each motor in a pair to achieve the specified
steering. Note that calling this function alone will not make the
motors move, it only sets the speed. A run_* function must be called
afterwards to make the motors move.

direction [-100, 100]:
* -100 means turn left as fast as possible,
* 0 means drive in a straight line, and
* 100 means turn right as fast as possible.

speed_outer_motor:
The speed that should be applied to the outmost motor (the one
rotating faster). The speed of the other motor will be computed
automatically.
"""

assert direction >= -100 and direction <= 100,\
"%s is an invalid direction, must be between -100 and 100 (inclusive)" % direction

left_speed = speed_outer_motor
right_speed = speed_outer_motor
speed = (50 - abs(float(direction))) / 50

if direction >= 0:
right_speed *= speed
else:
left_speed *= speed

left_speed = int(left_speed)
right_speed = int(right_speed)
self.left_motor.speed_sp = left_speed
self.right_motor.speed_sp = right_speed

log.debug("%s: direction %d, %s speed %d, %s speed %d" %
(self, direction, self.left_motor, left_speed, self.right_motor, right_speed))

def set_speed_percentage(self, left_motor_percentage, right_motor_percentage):
"""
Set the speeds of the left_motor vs right_motor by percentage of
their maximum speed. The minimum valid percentage is -100, the
maximum is 100.

Note that calling this function alone will not make the motors move, it
only sets the speed. A run_* function must be called afterwards to make
the motors move.
"""

assert left_motor_percentage >= -100 and left_motor_percentage <= 100,\
"%s is an invalid percentage, must be between -100 and 100 (inclusive)" % left_motor_percentage

assert right_motor_percentage >= -100 and right_motor_percentage <= 100,\
"%s is an invalid percentage, must be between -100 and 100 (inclusive)" % right_motor_percentage

# Convert left_motor_percentage and right_motor_percentage to fractions
left_motor_percentage = left_motor_percentage / 100.0
right_motor_percentage = right_motor_percentage / 100.0

self.left_motor.speed_sp = int(self.max_speed * left_motor_percentage)
self.right_motor.speed_sp = int(self.max_speed * right_motor_percentage)


class LargeMotorPair(MotorPair):

def __init__(self, left_motor, right_motor, desc=None):
motor_specs = {
left_motor : LargeMotor,
right_motor : LargeMotor,
}
MotorPair.__init__(self, motor_specs, desc)


class MediumMotorPair(MotorPair):

def __init__(self, left_motor, right_motor, desc=None):
motor_specs = {
left_motor : MediumMotor,
right_motor : MediumMotor,
}
MotorPair.__init__(self, motor_specs, desc)


class ColorSensorMixin(object):

def rgb(self):
Expand All @@ -167,57 +415,34 @@ class ColorSensor(ev3dev.auto.ColorSensor, ColorSensorMixin):
# ============
# Tank classes
# ============
class Tank(object):

def __init__(self, left_motor, right_motor, polarity='normal', name='Tank'):

for motor in (left_motor, right_motor):
if motor not in OUTPUTS:
log.error("%s in an invalid motor, choices are %s" % (motor, ', '.join(OUTPUTS)))
sys.exit(1)

self.left_motor = LargeMotor(left_motor)
self.right_motor = LargeMotor(right_motor)

for x in (self.left_motor, self.right_motor):
if not x.connected:
log.error("%s is not connected" % x)
sys.exit(1)
class Tank(LargeMotorPair):
"""
This class is here for backwards compatibility for anyone who was using
this library before the days of LargeMotorPair. We wrote the Tank class
first, then LargeMotorPair. All future work will be in the MotorSet,
MotorPair, etc classes
"""

self.left_motor.reset()
self.right_motor.reset()
self.speed_sp = 400
self.left_motor.speed_sp = self.speed_sp
self.right_motor.speed_sp = self.speed_sp
def __init__(self, left_motor_port, right_motor_port, polarity='normal', name='Tank'):
LargeMotorPair.__init__(self, left_motor_port, right_motor_port, name)
self.set_polarity(polarity)
self.name = name

def __str__(self):
return self.name

def set_polarity(self, polarity):
valid_choices = ('normal', 'inversed')
assert polarity in valid_choices,\
"%s is an invalid polarity choice, must be %s" % (polarity, ', '.join(valid_choices))
self.speed_sp = 400

self.left_motor.polarity = polarity
self.right_motor.polarity = polarity

class RemoteControlledTank(LargeMotorPair):

class RemoteControlledTank(Tank):
def __init__(self, left_motor_port, right_motor_port, polarity='inversed', speed=400):
LargeMotorPair.__init__(self, left_motor_port, right_motor_port)
self.set_polarity(polarity)

def __init__(self, left_motor, right_motor, polarity='inversed'):
Tank.__init__(self, left_motor, right_motor, polarity)
left_motor = self.motors[left_motor_port]
right_motor = self.motors[right_motor_port]
self.speed_sp = speed
self.remote = RemoteControl(channel=1)

if not self.remote.connected:
log.error("%s is not connected" % self.remote)
sys.exit(1)

self.remote.on_red_up = self.make_move(self.left_motor, self.speed_sp)
self.remote.on_red_down = self.make_move(self.left_motor, self.speed_sp * -1)
self.remote.on_blue_up = self.make_move(self.right_motor, self.speed_sp)
self.remote.on_blue_down = self.make_move(self.right_motor, self.speed_sp * -1)
self.remote.on_red_up = self.make_move(left_motor, self.speed_sp)
self.remote.on_red_down = self.make_move(left_motor, self.speed_sp* -1)
self.remote.on_blue_up = self.make_move(right_motor, self.speed_sp)
self.remote.on_blue_down = self.make_move(right_motor, self.speed_sp * -1)

def make_move(self, motor, dc_sp):
def move(state):
Expand All @@ -237,9 +462,7 @@ def main(self):
# Exit cleanly so that all motors are stopped
except (KeyboardInterrupt, Exception) as e:
log.exception(e)

for motor in list_motors():
motor.stop()
self.stop()


# =====================
Expand Down
Loading