Skip to content
1 change: 1 addition & 0 deletions debian/changelog
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
python-ev3dev2 (2.0.0~beta4) UNRELEASED; urgency=medium

[Daniel Walton]
* PID line follower
* micropython Button support
* micropython Sound support
* micropython support for LED animations
Expand Down
13 changes: 7 additions & 6 deletions ev3dev2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def _get_attribute(self, attribute, name):
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except Exception as ex:
self._raise_friendly_access_error(ex, name)
self._raise_friendly_access_error(ex, name, None)

def _set_attribute(self, attribute, name, value):
"""Device attribute setter"""
Expand All @@ -261,10 +261,10 @@ def _set_attribute(self, attribute, name, value):
attribute.write(value)
attribute.flush()
except Exception as ex:
self._raise_friendly_access_error(ex, name)
self._raise_friendly_access_error(ex, name, value)
return attribute

def _raise_friendly_access_error(self, driver_error, attribute):
def _raise_friendly_access_error(self, driver_error, attribute, value):
if not isinstance(driver_error, OSError):
raise driver_error

Expand All @@ -275,10 +275,11 @@ def _raise_friendly_access_error(self, driver_error, attribute):
try:
max_speed = self.max_speed
except (AttributeError, Exception):
chain_exception(ValueError("The given speed value was out of range"), driver_error)
chain_exception(ValueError("The given speed value {} was out of range".format(value)),
driver_error)
else:
chain_exception(ValueError("The given speed value was out of range. Max speed: +/-" + str(max_speed)), driver_error)
chain_exception(ValueError("One or more arguments were out of range or invalid"), driver_error)
chain_exception(ValueError("The given speed value {} was out of range. Max speed: +/-{}".format(value, max_speed)), driver_error)
chain_exception(ValueError("One or more arguments were out of range or invalid, value {}".format(value)), driver_error)
elif driver_errorno == errno.ENODEV or driver_errorno == errno.ENOENT:
# We will assume that a file-not-found error is the result of a disconnected device
# rather than a library error. If that isn't the case, at a minimum the underlying
Expand Down
192 changes: 185 additions & 7 deletions ev3dev2/motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from logging import getLogger
from os.path import abspath
from ev3dev2 import get_current_platform, Device, list_device_names
from ev3dev2.stopwatch import StopWatch

log = getLogger(__name__)

Expand Down Expand Up @@ -83,9 +84,24 @@ class SpeedValue(object):
:class:`SpeedDPS`, and :class:`SpeedDPM`.
"""

def __eq__(self, other):
return self.to_native_units() == other.to_native_units()

def __ne__(self, other):
Comment thread
dwalton76 marked this conversation as resolved.
Resolved
return not self.__eq__(other)

def __lt__(self, other):
return self.to_native_units() < other.to_native_units()

def __le__(self, other):
return self.to_native_units() <= other.to_native_units()

def __gt__(self, other):
return self.to_native_units() > other.to_native_units()

def __ge__(self, other):
return self.to_native_units() >= other.to_native_units()

def __rmul__(self, other):
return self.__mul__(other)

Expand Down Expand Up @@ -124,13 +140,13 @@ def __init__(self, native_counts):
self.native_counts = native_counts

def __str__(self):
return str(self.native_counts) + " counts/sec"
return "{:.2f}".format(self.native_counts) + " counts/sec"

def __mul__(self, other):
assert isinstance(other, (float, int)), "{} can only be multiplied by an int or float".format(self)
return SpeedNativeUnits(self.native_counts * other)

def to_native_units(self, motor):
def to_native_units(self, motor=None):
"""
Return this SpeedNativeUnits as a number
"""
Expand Down Expand Up @@ -1774,6 +1790,46 @@ def _block(self):
self.wait_until_not_moving()


# line follower classes
class LineFollowErrorLostLine(Exception):
"""
Raised when a line following robot has lost the line
"""
pass


class LineFollowErrorTooFast(Exception):
"""
Raised when a line following robot has been asked to follow
a line at an unrealistic speed
"""
pass


# line follower functions
def follow_for_forever(tank):
"""
``tank``: the MoveTank object that is following a line
"""
return True


def follow_for_ms(tank, ms):
"""
``tank``: the MoveTank object that is following a line
``ms`` : the number of milliseconds to follow the line
"""
if not hasattr(tank, 'stopwatch') or tank.stopwatch is None:
tank.stopwatch = StopWatch()
tank.stopwatch.start()

if tank.stopwatch.value_ms >= ms:
tank.stopwatch = None
return False
else:
return True


class MoveTank(MotorSet):
"""
Controls a pair of motors simultaneously, via individual speed setpoints for each motor.
Expand All @@ -1798,6 +1854,9 @@ def __init__(self, left_motor_port, right_motor_port, desc=None, motor_class=Lar
self.right_motor = self.motors[right_motor_port]
self.max_speed = self.left_motor.max_speed

# color sensor used by follow_line()
self.cs = None
Comment thread
dwalton76 marked this conversation as resolved.
Resolved

def _unpack_speeds_to_native_units(self, left_speed, right_speed):
left_speed = self.left_motor._speed_native_units(left_speed, "left_speed")
right_speed = self.right_motor._speed_native_units(right_speed, "right_speed")
Expand Down Expand Up @@ -1921,6 +1980,125 @@ def on(self, left_speed, right_speed):
self.left_motor.run_forever()
self.right_motor.run_forever()

def follow_line(self,
kp, ki, kd,
Comment thread
dwalton76 marked this conversation as resolved.
Resolved
speed,
target_light_intensity=None,
follow_left_edge=True,
white=60,
off_line_count_max=20,
sleep_time=0.01,
follow_for=follow_for_forever,
**kwargs
):
"""
PID line follower
``kp``, ``ki``, and ``kd`` are the PID constants.
``speed`` is the desired speed of the midpoint of the robot
``target_light_intensity`` is the reflected light intensity when the color sensor
is on the edge of the line. If this is None we assume that the color sensor
is on the edge of the line and will take a reading to set this variable.
``follow_left_edge`` determines if we follow the left or right edge of the line
``white`` is the reflected_light_intensity that is used to determine if we have
lost the line
``off_line_count_max`` is how many consecutive times through the loop the
reflected_light_intensity must be greater than ``white`` before we
declare the line lost and raise an exception
``sleep_time`` is how many seconds we sleep on each pass through
the loop. This is to give the robot a chance to react
to the new motor settings. This should be something small such
as 0.01 (10ms).
``follow_for`` is called to determine if we should keep following the
line or stop. This function will be passed ``self`` (the current
``MoveTank`` object). Current supported options are:
- ``follow_for_forever``
- ``follow_for_ms``
``**kwargs`` will be passed to the ``follow_for`` function
Example:
.. code:: python
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, MoveTank, SpeedPercent, follow_for_ms
from ev3dev2.sensor.lego import ColorSensor
tank = MoveTank(OUTPUT_A, OUTPUT_B)
tank.cs = ColorSensor()
try:
# Follow the line for 4500ms
tank.follow_line(
kp=11.3, ki=0.05, kd=3.2,
speed=SpeedPercent(30),
follow_for=follow_for_ms,
ms=4500
)
except Exception:
tank.stop()
raise
"""
assert self.cs, "ColorSensor must be defined"

if target_light_intensity is None:
target_light_intensity = self.cs.reflected_light_intensity

integral = 0.0
last_error = 0.0
derivative = 0.0
off_line_count = 0
speed_native_units = speed.to_native_units(self.left_motor)
MAX_SPEED = SpeedNativeUnits(self.max_speed)

while follow_for(self, **kwargs):
reflected_light_intensity = self.cs.reflected_light_intensity
error = target_light_intensity - reflected_light_intensity
integral = integral + error
Comment thread
dwalton76 marked this conversation as resolved.
Resolved
derivative = error - last_error
last_error = error
turn_native_units = (kp * error) + (ki * integral) + (kd * derivative)

if not follow_left_edge:
turn_native_units *= -1

left_speed = SpeedNativeUnits(speed_native_units - turn_native_units)
right_speed = SpeedNativeUnits(speed_native_units + turn_native_units)

if left_speed > MAX_SPEED:
log.info("%s: left_speed %s is greater than MAX_SPEED %s" % (self, left_speed, MAX_SPEED))
self.stop()
raise LineFollowErrorTooFast("The robot is moving too fast to follow the line")

if right_speed > MAX_SPEED:
log.info("%s: right_speed %s is greater than MAX_SPEED %s" % (self, right_speed, MAX_SPEED))
self.stop()
raise LineFollowErrorTooFast("The robot is moving too fast to follow the line")

# Have we lost the line?
if reflected_light_intensity >= white:
off_line_count += 1

if off_line_count >= off_line_count_max:
self.stop()
Comment thread
dwalton76 marked this conversation as resolved.
Resolved
raise LineFollowErrorLostLine("we lost the line")
else:
off_line_count = 0

if sleep_time:
time.sleep(sleep_time)

self.on(left_speed, right_speed)

self.stop()


class MoveSteering(MoveTank):
"""
Expand Down Expand Up @@ -2224,7 +2402,7 @@ def odometry_coordinates_log(self):

def odometry_start(self, theta_degrees_start=90.0,
x_pos_start=0.0, y_pos_start=0.0,
SLEEP_TIME=0.005): # 5ms
sleep_time=0.005): # 5ms
"""
Ported from:
http://seattlerobotics.org/encoder/200610/Article3/IMU%20Odometry,%20by%20David%20Anderson.htm
Expand Down Expand Up @@ -2254,8 +2432,8 @@ def _odometry_monitor():

# Have we moved?
if not left_ticks and not right_ticks:
if SLEEP_TIME:
time.sleep(SLEEP_TIME)
if sleep_time:
time.sleep(sleep_time)
continue

# log.debug("%s: left_ticks %s (from %s to %s)" %
Expand Down Expand Up @@ -2288,8 +2466,8 @@ def _odometry_monitor():
self.x_pos_mm += mm * math.cos(self.theta)
self.y_pos_mm += mm * math.sin(self.theta)

if SLEEP_TIME:
time.sleep(SLEEP_TIME)
if sleep_time:
time.sleep(sleep_time)

self.odometry_thread_id = None

Expand Down
Loading