INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Writing sets the ramp down setpoint. Reading returns the current value. Units are in milliseconds and must be positive. When set to a non-zero value, the motor speed will decrease from 0 to 100% of `max_speed` over the span of this setpoint. The actual ramp time is the ratio of the difference between the `speed_sp` and the current `speed` and max_speed multiplied by `ramp_down_sp`.
def ramp_down_sp(self): """ Writing sets the ramp down setpoint. Reading returns the current value. Units are in milliseconds and must be positive. When set to a non-zero value, the motor speed will decrease from 0 to 100% of `max_speed` over the span of this setpoint. The actual ramp time is the ratio of the difference between the `speed_sp` and the current `speed` and max_speed multiplied by `ramp_down_sp`. """ self._ramp_down_sp, value = self.get_attr_int(self._ramp_down_sp, 'ramp_down_sp') return value
The proportional constant for the speed regulation PID.
def speed_p(self): """ The proportional constant for the speed regulation PID. """ self._speed_p, value = self.get_attr_int(self._speed_p, 'speed_pid/Kp') return value
The integral constant for the speed regulation PID.
def speed_i(self): """ The integral constant for the speed regulation PID. """ self._speed_i, value = self.get_attr_int(self._speed_i, 'speed_pid/Ki') return value
The derivative constant for the speed regulation PID.
def speed_d(self): """ The derivative constant for the speed regulation PID. """ self._speed_d, value = self.get_attr_int(self._speed_d, 'speed_pid/Kd') return value
Reading returns a list of state flags. Possible flags are `running`, `ramping`, `holding`, `overloaded` and `stalled`.
def state(self): """ Reading returns a list of state flags. Possible flags are `running`, `ramping`, `holding`, `overloaded` and `stalled`. """ self._state, value = self.get_attr_set(self._state, 'state') return value
Reading returns the current stop action. Writing sets the stop action. The value determines the motors behavior when `command` is set to `stop`. Also, it determines the motors behavior when a run command completes. See `stop_actions` for a list of possible values.
def stop_action(self): """ Reading returns the current stop action. Writing sets the stop action. The value determines the motors behavior when `command` is set to `stop`. Also, it determines the motors behavior when a run command completes. See `stop_actions` for a list of possible values. """ self._stop_action, value = self.get_attr_string(self._stop_action, 'stop_action') return value
Returns a list of stop actions supported by the motor controller. Possible values are `coast`, `brake` and `hold`. `coast` means that power will be removed from the motor and it will freely coast to a stop. `brake` means that power will be removed from the motor and a passive electrical load will be placed on the motor. This is usually done by shorting the motor terminals together. This load will absorb the energy from the rotation of the motors and cause the motor to stop more quickly than coasting. `hold` does not remove power from the motor. Instead it actively tries to hold the motor at the current position. If an external force tries to turn the motor, the motor will 'push back' to maintain its position.
def stop_actions(self): """ Returns a list of stop actions supported by the motor controller. Possible values are `coast`, `brake` and `hold`. `coast` means that power will be removed from the motor and it will freely coast to a stop. `brake` means that power will be removed from the motor and a passive electrical load will be placed on the motor. This is usually done by shorting the motor terminals together. This load will absorb the energy from the rotation of the motors and cause the motor to stop more quickly than coasting. `hold` does not remove power from the motor. Instead it actively tries to hold the motor at the current position. If an external force tries to turn the motor, the motor will 'push back' to maintain its position. """ (self._stop_actions, value) = self.get_cached_attr_set(self._stop_actions, 'stop_actions') return value
Writing specifies the amount of time the motor will run when using the `run-timed` command. Reading returns the current value. Units are in milliseconds.
def time_sp(self): """ Writing specifies the amount of time the motor will run when using the `run-timed` command. Reading returns the current value. Units are in milliseconds. """ self._time_sp, value = self.get_attr_int(self._time_sp, 'time_sp') return value
Run the motor until another command is sent.
def run_forever(self, **kwargs): """ Run the motor until another command is sent. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_FOREVER
Run to an absolute position specified by `position_sp` and then stop using the action specified in `stop_action`.
def run_to_abs_pos(self, **kwargs): """ Run to an absolute position specified by `position_sp` and then stop using the action specified in `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TO_ABS_POS
Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`.
def run_to_rel_pos(self, **kwargs): """ Run to a position relative to the current `position` value. The new position will be current `position` + `position_sp`. When the new position is reached, the motor will stop using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TO_REL_POS
Run the motor for the amount of time specified in `time_sp` and then stop the motor using the action specified by `stop_action`.
def run_timed(self, **kwargs): """ Run the motor for the amount of time specified in `time_sp` and then stop the motor using the action specified by `stop_action`. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_TIMED
Run the motor at the duty cycle specified by `duty_cycle_sp`. Unlike other run commands, changing `duty_cycle_sp` while running *will* take effect immediately.
def run_direct(self, **kwargs): """ Run the motor at the duty cycle specified by `duty_cycle_sp`. Unlike other run commands, changing `duty_cycle_sp` while running *will* take effect immediately. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_DIRECT
Reset all of the motor parameter attributes to their default value. This will also have the effect of stopping the motor.
def reset(self, **kwargs): """ Reset all of the motor parameter attributes to their default value. This will also have the effect of stopping the motor. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RESET
Blocks until ``cond(self.state)`` is ``True``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached.
def wait(self, cond, timeout=None): """ Blocks until ``cond(self.state)`` is ``True``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached. """ tic = time.time() if self._poll is None: if self._state is None: self._state = self._attribute_file_open('state') self._poll = select.poll() self._poll.register(self._state, select.POLLPRI) # Set poll timeout to something small. For more details, see # https://github.com/ev3dev/ev3dev-lang-python/issues/583 if timeout: poll_tm = min(timeout, 100) else: poll_tm = 100 while True: # This check is now done every poll_tm even if poll has nothing to report: if cond(self.state): return True self._poll.poll(poll_tm) if timeout is not None and time.time() >= tic + timeout / 1000: # Final check when user timeout is reached return cond(self.state)
Blocks until ``running`` is not in ``self.state`` or ``stalled`` is in ``self.state``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached. Example:: m.wait_until_not_moving()
def wait_until_not_moving(self, timeout=None): """ Blocks until ``running`` is not in ``self.state`` or ``stalled`` is in ``self.state``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached. Example:: m.wait_until_not_moving() """ return self.wait(lambda state: self.STATE_RUNNING not in state or self.STATE_STALLED in state, timeout)
Blocks until ``s`` is in ``self.state``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached. Example:: m.wait_until('stalled')
def wait_until(self, s, timeout=None): """ Blocks until ``s`` is in ``self.state``. The condition is checked when there is an I/O event related to the ``state`` attribute. Exits early when ``timeout`` (in milliseconds) is reached. Returns ``True`` if the condition is met, and ``False`` if the timeout is reached. Example:: m.wait_until('stalled') """ return self.wait(lambda state: s in state, timeout)
Rotate the motor at ``speed`` for ``rotations`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units.
def on_for_rotations(self, speed, rotations, brake=True, block=True): """ Rotate the motor at ``speed`` for ``rotations`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ speed_sp = self._speed_native_units(speed) self._set_rel_position_degrees_and_speed_sp(rotations * 360, speed_sp) self._set_brake(brake) self.run_to_rel_pos() if block: self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT) self.wait_until_not_moving()
Rotate the motor at ``speed`` for ``degrees`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units.
def on_for_degrees(self, speed, degrees, brake=True, block=True): """ Rotate the motor at ``speed`` for ``degrees`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ speed_sp = self._speed_native_units(speed) self._set_rel_position_degrees_and_speed_sp(degrees, speed_sp) self._set_brake(brake) self.run_to_rel_pos() if block: self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT) self.wait_until_not_moving()
Rotate the motor at ``speed`` to ``position`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units.
def on_to_position(self, speed, position, brake=True, block=True): """ Rotate the motor at ``speed`` to ``position`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ speed = self._speed_native_units(speed) self.speed_sp = int(round(speed)) self.position_sp = position self._set_brake(brake) self.run_to_abs_pos() if block: self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT) self.wait_until_not_moving()
Rotate the motor at ``speed`` for ``seconds`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units.
def on_for_seconds(self, speed, seconds, brake=True, block=True): """ Rotate the motor at ``speed`` for ``seconds`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ if seconds < 0: raise ValueError("seconds is negative ({})".format(seconds)) speed = self._speed_native_units(speed) self.speed_sp = int(round(speed)) self.time_sp = int(seconds * 1000) self._set_brake(brake) self.run_timed() if block: self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT) self.wait_until_not_moving()
Rotate the motor at ``speed`` for forever ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. Note that `block` is False by default, this is different from the other `on_for_XYZ` methods.
def on(self, speed, brake=True, block=False): """ Rotate the motor at ``speed`` for forever ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. Note that `block` is False by default, this is different from the other `on_for_XYZ` methods. """ speed = self._speed_native_units(speed) self.speed_sp = int(round(speed)) self._set_brake(brake) self.run_forever() if block: self.wait_until('running', timeout=WAIT_RUNNING_TIMEOUT) self.wait_until_not_moving()
Returns a list of commands supported by the motor controller.
def commands(self): """ Returns a list of commands supported by the motor controller. """ self._commands, value = self.get_attr_set(self._commands, 'commands') return value
Returns the name of the motor driver that loaded this device. See the list of [supported devices] for a list of drivers.
def driver_name(self): """ Returns the name of the motor driver that loaded this device. See the list of [supported devices] for a list of drivers. """ self._driver_name, value = self.get_attr_string(self._driver_name, 'driver_name') return value
Gets a list of stop actions. Valid values are `coast` and `brake`.
def stop_actions(self): """ Gets a list of stop actions. Valid values are `coast` and `brake`. """ self._stop_actions, value = self.get_attr_set(self._stop_actions, 'stop_actions') return value
Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the maximum (clockwise) position_sp. Default value is 2400. Valid values are 2300 to 2700. You must write to the position_sp attribute for changes to this attribute to take effect.
def max_pulse_sp(self): """ Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the maximum (clockwise) position_sp. Default value is 2400. Valid values are 2300 to 2700. You must write to the position_sp attribute for changes to this attribute to take effect. """ self._max_pulse_sp, value = self.get_attr_int(self._max_pulse_sp, 'max_pulse_sp') return value
Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the mid position_sp. Default value is 1500. Valid values are 1300 to 1700. For example, on a 180 degree servo, this would be 90 degrees. On continuous rotation servo, this is the 'neutral' position_sp where the motor does not turn. You must write to the position_sp attribute for changes to this attribute to take effect.
def mid_pulse_sp(self): """ Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the mid position_sp. Default value is 1500. Valid values are 1300 to 1700. For example, on a 180 degree servo, this would be 90 degrees. On continuous rotation servo, this is the 'neutral' position_sp where the motor does not turn. You must write to the position_sp attribute for changes to this attribute to take effect. """ self._mid_pulse_sp, value = self.get_attr_int(self._mid_pulse_sp, 'mid_pulse_sp') return value
Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the miniumum (counter-clockwise) position_sp. Default value is 600. Valid values are 300 to 700. You must write to the position_sp attribute for changes to this attribute to take effect.
def min_pulse_sp(self): """ Used to set the pulse size in milliseconds for the signal that tells the servo to drive to the miniumum (counter-clockwise) position_sp. Default value is 600. Valid values are 300 to 700. You must write to the position_sp attribute for changes to this attribute to take effect. """ self._min_pulse_sp, value = self.get_attr_int(self._min_pulse_sp, 'min_pulse_sp') return value
Sets the rate_sp at which the servo travels from 0 to 100.0% (half of the full range of the servo). Units are in milliseconds. Example: Setting the rate_sp to 1000 means that it will take a 180 degree servo 2 second to move from 0 to 180 degrees. Note: Some servo controllers may not support this in which case reading and writing will fail with `-EOPNOTSUPP`. In continuous rotation servos, this value will affect the rate_sp at which the speed ramps up or down.
def rate_sp(self): """ Sets the rate_sp at which the servo travels from 0 to 100.0% (half of the full range of the servo). Units are in milliseconds. Example: Setting the rate_sp to 1000 means that it will take a 180 degree servo 2 second to move from 0 to 180 degrees. Note: Some servo controllers may not support this in which case reading and writing will fail with `-EOPNOTSUPP`. In continuous rotation servos, this value will affect the rate_sp at which the speed ramps up or down. """ self._rate_sp, value = self.get_attr_int(self._rate_sp, 'rate_sp') return value
Drive servo to the position set in the `position_sp` attribute.
def run(self, **kwargs): """ Drive servo to the position set in the `position_sp` attribute. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN
Remove power from the motor.
def float(self, **kwargs): """ Remove power from the motor. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_FLOAT
Stop motors immediately. Configure motors to brake if ``brake`` is set.
def off(self, motors=None, brake=True): """ Stop motors immediately. Configure motors to brake if ``brake`` is set. """ motors = motors if motors is not None else self.motors.values() for motor in motors: motor._set_brake(brake) for motor in motors: motor.stop()
Rotate the motors at 'left_speed & right_speed' for 'degrees'. Speeds can be percentages or any SpeedValue implementation. If the left speed is not equal to the right speed (i.e., the robot will turn), the motor on the outside of the turn will rotate for the full ``degrees`` while the motor on the inside will have its requested distance calculated according to the expected turn.
def on_for_degrees(self, left_speed, right_speed, degrees, brake=True, block=True): """ Rotate the motors at 'left_speed & right_speed' for 'degrees'. Speeds can be percentages or any SpeedValue implementation. If the left speed is not equal to the right speed (i.e., the robot will turn), the motor on the outside of the turn will rotate for the full ``degrees`` while the motor on the inside will have its requested distance calculated according to the expected turn. """ (left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed) # proof of the following distance calculation: consider the circle formed by each wheel's path # v_l = d_l/t, v_r = d_r/t # therefore, t = d_l/v_l = d_r/v_r if degrees == 0 or (left_speed_native_units == 0 and right_speed_native_units == 0): left_degrees = degrees right_degrees = degrees # larger speed by magnitude is the "outer" wheel, and rotates the full "degrees" elif abs(left_speed_native_units) > abs(right_speed_native_units): left_degrees = degrees right_degrees = abs(right_speed_native_units / left_speed_native_units) * degrees else: left_degrees = abs(left_speed_native_units / right_speed_native_units) * degrees right_degrees = degrees # Set all parameters self.left_motor._set_rel_position_degrees_and_speed_sp(left_degrees, left_speed_native_units) self.left_motor._set_brake(brake) self.right_motor._set_rel_position_degrees_and_speed_sp(right_degrees, right_speed_native_units) self.right_motor._set_brake(brake) log.debug("{}: on_for_degrees {}".format(self, degrees)) # These debugs involve disk I/O to pull position and position_sp so only uncomment # if you need to troubleshoot in more detail. # log.debug("{}: left_speed {}, left_speed_native_units {}, left_degrees {}, left-position {}->{}".format( # self, left_speed, left_speed_native_units, left_degrees, # self.left_motor.position, self.left_motor.position_sp)) # log.debug("{}: right_speed {}, right_speed_native_units {}, right_degrees {}, right-position {}->{}".format( # self, right_speed, right_speed_native_units, right_degrees, # self.right_motor.position, self.right_motor.position_sp)) # Start the motors self.left_motor.run_to_rel_pos() self.right_motor.run_to_rel_pos() if block: self._block()
Rotate the motors at 'left_speed & right_speed' for 'rotations'. Speeds can be percentages or any SpeedValue implementation. If the left speed is not equal to the right speed (i.e., the robot will turn), the motor on the outside of the turn will rotate for the full ``rotations`` while the motor on the inside will have its requested distance calculated according to the expected turn.
def on_for_rotations(self, left_speed, right_speed, rotations, brake=True, block=True): """ Rotate the motors at 'left_speed & right_speed' for 'rotations'. Speeds can be percentages or any SpeedValue implementation. If the left speed is not equal to the right speed (i.e., the robot will turn), the motor on the outside of the turn will rotate for the full ``rotations`` while the motor on the inside will have its requested distance calculated according to the expected turn. """ MoveTank.on_for_degrees(self, left_speed, right_speed, rotations * 360, brake, block)
Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds can be percentages or any SpeedValue implementation.
def on_for_seconds(self, left_speed, right_speed, seconds, brake=True, block=True): """ Rotate the motors at 'left_speed & right_speed' for 'seconds'. Speeds can be percentages or any SpeedValue implementation. """ if seconds < 0: raise ValueError("seconds is negative ({})".format(seconds)) (left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed) # Set all parameters self.left_motor.speed_sp = int(round(left_speed_native_units)) self.left_motor.time_sp = int(seconds * 1000) self.left_motor._set_brake(brake) self.right_motor.speed_sp = int(round(right_speed_native_units)) self.right_motor.time_sp = int(seconds * 1000) self.right_motor._set_brake(brake) log.debug("%s: on_for_seconds %ss at left-speed %s, right-speed %s" % (self, seconds, left_speed, right_speed)) # Start the motors self.left_motor.run_timed() self.right_motor.run_timed() if block: self._block()
Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation.
def on(self, left_speed, right_speed): """ Start rotating the motors according to ``left_speed`` and ``right_speed`` forever. Speeds can be percentages or any SpeedValue implementation. """ (left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed) # Set all parameters self.left_motor.speed_sp = int(round(left_speed_native_units)) self.right_motor.speed_sp = int(round(right_speed_native_units)) # This debug involves disk I/O to pull speed_sp so only uncomment # if you need to troubleshoot in more detail. # log.debug("%s: on at left-speed %s, right-speed %s" % # (self, self.left_motor.speed_sp, self.right_motor.speed_sp)) # Start the motors self.left_motor.run_forever() self.right_motor.run_forever()
Rotate the motors according to the provided ``steering``. The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_rotations`.
def on_for_rotations(self, steering, speed, rotations, brake=True, block=True): """ Rotate the motors according to the provided ``steering``. The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_rotations`. """ (left_speed, right_speed) = self.get_speed_steering(steering, speed) MoveTank.on_for_rotations(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), rotations, brake, block)
Rotate the motors according to the provided ``steering``. The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_degrees`.
def on_for_degrees(self, steering, speed, degrees, brake=True, block=True): """ Rotate the motors according to the provided ``steering``. The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_degrees`. """ (left_speed, right_speed) = self.get_speed_steering(steering, speed) MoveTank.on_for_degrees(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), degrees, brake, block)
Rotate the motors according to the provided ``steering`` for ``seconds``.
def on_for_seconds(self, steering, speed, seconds, brake=True, block=True): """ Rotate the motors according to the provided ``steering`` for ``seconds``. """ (left_speed, right_speed) = self.get_speed_steering(steering, speed) MoveTank.on_for_seconds(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), seconds, brake, block)
Start rotating the motors according to the provided ``steering`` and ``speed`` forever.
def on(self, steering, speed): """ Start rotating the motors according to the provided ``steering`` and ``speed`` forever. """ (left_speed, right_speed) = self.get_speed_steering(steering, speed) MoveTank.on(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed))
Calculate 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 calculates the speed. A run_* function must be called afterwards to make the motors move. steering [-100, 100]: * -100 means turn left on the spot (right motor at 100% forward, left motor at 100% backward), * 0 means drive in a straight line, and * 100 means turn right on the spot (left motor at 100% forward, right motor at 100% backward). speed: The speed that should be applied to the outmost motor (the one rotating faster). The speed of the other motor will be computed automatically.
def get_speed_steering(self, steering, speed): """ Calculate 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 calculates the speed. A run_* function must be called afterwards to make the motors move. steering [-100, 100]: * -100 means turn left on the spot (right motor at 100% forward, left motor at 100% backward), * 0 means drive in a straight line, and * 100 means turn right on the spot (left motor at 100% forward, right motor at 100% backward). speed: 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 steering >= -100 and steering <= 100,\ "{} is an invalid steering, must be between -100 and 100 (inclusive)".format(steering) # We don't have a good way to make this generic for the pair... so we # assume that the left motor's speed stats are the same as the right # motor's. speed = self.left_motor._speed_native_units(speed) left_speed = speed right_speed = speed speed_factor = (50 - abs(float(steering))) / 50 if steering >= 0: right_speed *= speed_factor else: left_speed *= speed_factor return (left_speed, right_speed)
Drive distance_mm
def on_for_distance(self, speed, distance_mm, brake=True, block=True): """ Drive distance_mm """ rotations = distance_mm / self.wheel.circumference_mm log.debug("%s: on_for_rotations distance_mm %s, rotations %s, speed %s" % (self, distance_mm, rotations, speed)) MoveTank.on_for_rotations(self, speed, speed, rotations, brake, block)
Drive in a circle with 'radius' for 'distance'
def _on_arc(self, speed, radius_mm, distance_mm, brake, block, arc_right): """ Drive in a circle with 'radius' for 'distance' """ if radius_mm < self.min_circle_radius_mm: raise ValueError("{}: radius_mm {} is less than min_circle_radius_mm {}" .format( self, radius_mm, self.min_circle_radius_mm)) # The circle formed at the halfway point between the two wheels is the # circle that must have a radius of radius_mm circle_outer_mm = 2 * math.pi * (radius_mm + (self.wheel_distance_mm / 2)) circle_middle_mm = 2 * math.pi * radius_mm circle_inner_mm = 2 * math.pi * (radius_mm - (self.wheel_distance_mm / 2)) if arc_right: # The left wheel is making the larger circle and will move at 'speed' # The right wheel is making a smaller circle so its speed will be a fraction of the left motor's speed left_speed = speed right_speed = float(circle_inner_mm/circle_outer_mm) * left_speed else: # The right wheel is making the larger circle and will move at 'speed' # The left wheel is making a smaller circle so its speed will be a fraction of the right motor's speed right_speed = speed left_speed = float(circle_inner_mm/circle_outer_mm) * right_speed log.debug("%s: arc %s, radius %s, distance %s, left-speed %s, right-speed %s, circle_outer_mm %s, circle_middle_mm %s, circle_inner_mm %s" % (self, "right" if arc_right else "left", radius_mm, distance_mm, left_speed, right_speed, circle_outer_mm, circle_middle_mm, circle_inner_mm ) ) # We know we want the middle circle to be of length distance_mm so # calculate the percentage of circle_middle_mm we must travel for the # middle of the robot to travel distance_mm. circle_middle_percentage = float(distance_mm / circle_middle_mm) # Now multiple that percentage by circle_outer_mm to calculate how # many mm the outer wheel should travel. circle_outer_final_mm = circle_middle_percentage * circle_outer_mm outer_wheel_rotations = float(circle_outer_final_mm / self.wheel.circumference_mm) outer_wheel_degrees = outer_wheel_rotations * 360 log.debug("%s: arc %s, circle_middle_percentage %s, circle_outer_final_mm %s, outer_wheel_rotations %s, outer_wheel_degrees %s" % (self, "right" if arc_right else "left", circle_middle_percentage, circle_outer_final_mm, outer_wheel_rotations, outer_wheel_degrees ) ) MoveTank.on_for_degrees(self, left_speed, right_speed, outer_wheel_degrees, brake, block)
Drive clockwise in a circle with 'radius_mm' for 'distance_mm'
def on_arc_right(self, speed, radius_mm, distance_mm, brake=True, block=True): """ Drive clockwise in a circle with 'radius_mm' for 'distance_mm' """ self._on_arc(speed, radius_mm, distance_mm, brake, block, True)
Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm'
def on_arc_left(self, speed, radius_mm, distance_mm, brake=True, block=True): """ Drive counter-clockwise in a circle with 'radius_mm' for 'distance_mm' """ self._on_arc(speed, radius_mm, distance_mm, brake, block, False)
Rotate in place 'degrees'. Both wheels must turn at the same speed for us to rotate in place.
def _turn(self, speed, degrees, brake=True, block=True): """ Rotate in place 'degrees'. Both wheels must turn at the same speed for us to rotate in place. """ # The distance each wheel needs to travel distance_mm = (abs(degrees) / 360) * self.circumference_mm # The number of rotations to move distance_mm rotations = distance_mm/self.wheel.circumference_mm log.debug("%s: turn() degrees %s, distance_mm %s, rotations %s, degrees %s" % (self, degrees, distance_mm, rotations, degrees)) # If degrees is positive rotate clockwise if degrees > 0: MoveTank.on_for_rotations(self, speed, speed * -1, rotations, brake, block) # If degrees is negative rotate counter-clockwise else: rotations = distance_mm / self.wheel.circumference_mm MoveTank.on_for_rotations(self, speed * -1, speed, rotations, brake, block)
Rotate clockwise 'degrees' in place
def turn_right(self, speed, degrees, brake=True, block=True): """ Rotate clockwise 'degrees' in place """ self._turn(speed, abs(degrees), brake, block)
Ported from: http://seattlerobotics.org/encoder/200610/Article3/IMU%20Odometry,%20by%20David%20Anderson.htm A thread is started that will run until the user calls odometry_stop() which will set odometry_thread_run to False
def odometry_start(self, theta_degrees_start=90.0, x_pos_start=0.0, y_pos_start=0.0, SLEEP_TIME=0.005): # 5ms """ Ported from: http://seattlerobotics.org/encoder/200610/Article3/IMU%20Odometry,%20by%20David%20Anderson.htm A thread is started that will run until the user calls odometry_stop() which will set odometry_thread_run to False """ def _odometry_monitor(): left_previous = 0 right_previous = 0 self.theta = math.radians(theta_degrees_start) # robot heading self.x_pos_mm = x_pos_start # robot X position in mm self.y_pos_mm = y_pos_start # robot Y position in mm TWO_PI = 2 * math.pi while self.odometry_thread_run: # sample the left and right encoder counts as close together # in time as possible left_current = self.left_motor.position right_current = self.right_motor.position # determine how many ticks since our last sampling left_ticks = left_current - left_previous right_ticks = right_current - right_previous # Have we moved? if not left_ticks and not right_ticks: if SLEEP_TIME: time.sleep(SLEEP_TIME) continue # log.debug("%s: left_ticks %s (from %s to %s)" % # (self, left_ticks, left_previous, left_current)) # log.debug("%s: right_ticks %s (from %s to %s)" % # (self, right_ticks, right_previous, right_current)) # update _previous for next time left_previous = left_current right_previous = right_current # rotations = distance_mm/self.wheel.circumference_mm left_rotations = float(left_ticks / self.left_motor.count_per_rot) right_rotations = float(right_ticks / self.right_motor.count_per_rot) # convert longs to floats and ticks to mm left_mm = float(left_rotations * self.wheel.circumference_mm) right_mm = float(right_rotations * self.wheel.circumference_mm) # calculate distance we have traveled since last sampling mm = (left_mm + right_mm) / 2.0 # accumulate total rotation around our center self.theta += (right_mm - left_mm) / self.wheel_distance_mm # and clip the rotation to plus or minus 360 degrees self.theta -= float(int(self.theta/TWO_PI) * TWO_PI) # now calculate and accumulate our position in mm 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) self.odometry_thread_id = None self.odometry_thread_run = True self.odometry_thread_id = _thread.start_new_thread(_odometry_monitor, ())
Rotate in place to `angle_target_degrees` at `speed`
def turn_to_angle(self, speed, angle_target_degrees, brake=True, block=True): """ Rotate in place to `angle_target_degrees` at `speed` """ assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates" # Make both target and current angles positive numbers between 0 and 360 if angle_target_degrees < 0: angle_target_degrees += 360 angle_current_degrees = math.degrees(self.theta) if angle_current_degrees < 0: angle_current_degrees += 360 # Is it shorter to rotate to the right or left # to reach angle_target_degrees? if angle_current_degrees > angle_target_degrees: turn_right = True angle_delta = angle_current_degrees - angle_target_degrees else: turn_right = False angle_delta = angle_target_degrees - angle_current_degrees if angle_delta > 180: angle_delta = 360 - angle_delta turn_right = not turn_right log.debug("%s: turn_to_angle %s, current angle %s, delta %s, turn_right %s" % (self, angle_target_degrees, angle_current_degrees, angle_delta, turn_right)) self.odometry_coordinates_log() if turn_right: self.turn_right(speed, angle_delta, brake, block) else: self.turn_left(speed, angle_delta, brake, block) self.odometry_coordinates_log()
Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed`
def on_to_coordinates(self, speed, x_target_mm, y_target_mm, brake=True, block=True): """ Drive to (`x_target_mm`, `y_target_mm`) coordinates at `speed` """ assert self.odometry_thread_id, "odometry_start() must be called to track robot coordinates" # stop moving self.off(brake='hold') # rotate in place so we are pointed straight at our target x_delta = x_target_mm - self.x_pos_mm y_delta = y_target_mm - self.y_pos_mm angle_target_radians = math.atan2(y_delta, x_delta) angle_target_degrees = math.degrees(angle_target_radians) self.turn_to_angle(speed, angle_target_degrees, brake=True, block=True) # drive in a straight line to the target coordinates distance_mm = math.sqrt(pow(self.x_pos_mm - x_target_mm, 2) + pow(self.y_pos_mm - y_target_mm, 2)) self.on_for_distance(speed, distance_mm, brake, block)
Convert x,y joystick coordinates to left/right motor speed percentages and move the motors. This will use a classic "arcade drive" algorithm: a full-forward joystick goes straight forward and likewise for full-backward. Pushing the joystick all the way to one side will make it turn on the spot in that direction. Positions in the middle will control how fast the vehicle moves and how sharply it turns. "x", "y": The X and Y coordinates of the joystick's position, with (0,0) representing the center position. X is horizontal and Y is vertical. radius (default 100): The radius of the joystick, controlling the range of the input (x, y) values. e.g. if "x" and "y" can be between -1 and 1, radius should be set to "1".
def on(self, x, y, radius=100.0): """ Convert x,y joystick coordinates to left/right motor speed percentages and move the motors. This will use a classic "arcade drive" algorithm: a full-forward joystick goes straight forward and likewise for full-backward. Pushing the joystick all the way to one side will make it turn on the spot in that direction. Positions in the middle will control how fast the vehicle moves and how sharply it turns. "x", "y": The X and Y coordinates of the joystick's position, with (0,0) representing the center position. X is horizontal and Y is vertical. radius (default 100): The radius of the joystick, controlling the range of the input (x, y) values. e.g. if "x" and "y" can be between -1 and 1, radius should be set to "1". """ # If joystick is in the middle stop the tank if not x and not y: self.off() return vector_length = math.sqrt((x * x) + (y * y)) angle = math.degrees(math.atan2(y, x)) if angle < 0: angle += 360 # Should not happen but can happen (just by a hair) due to floating point math if vector_length > radius: vector_length = radius (init_left_speed_percentage, init_right_speed_percentage) = MoveJoystick.angle_to_speed_percentage(angle) # scale the speed percentages based on vector_length vs. radius left_speed_percentage = (init_left_speed_percentage * vector_length) / radius right_speed_percentage = (init_right_speed_percentage * vector_length) / radius # log.debug(""" # x, y : %s, %s # radius : %s # angle : %s # vector length : %s # init left_speed_percentage : %s # init right_speed_percentage : %s # final left_speed_percentage : %s # final right_speed_percentage : %s # """ % (x, y, radius, angle, vector_length, # init_left_speed_percentage, init_right_speed_percentage, # left_speed_percentage, right_speed_percentage)) MoveTank.on(self, SpeedPercent(left_speed_percentage), SpeedPercent(right_speed_percentage))
The following graphic illustrates the **motor power outputs** for the left and right motors based on where the joystick is pointing, of the form ``(left power, right power)``:: (1, 1) . . . . . . . . | . . | . (0, 1) . | . (1, 0) . | . . | . . | . . | . . | . . | x-axis . (-1, 1) .---------------------------------------. (1, -1) . | . . | . . | . . | y-axis . . | . (0, -1) . | . (-1, 0) . | . . | . . . . . . . . (-1, -1) The joystick is a circle within a circle where the (x, y) coordinates of the joystick form an angle with the x-axis. Our job is to translate this angle into the percentage of power that should be sent to each motor. For instance if the joystick is moved all the way to the top of the circle we want both motors to move forward with 100% power...that is represented above by (1, 1). If the joystick is moved all the way to the right side of the circle we want to rotate clockwise so we move the left motor forward 100% and the right motor backwards 100%...so (1, -1). If the joystick is at 45 degrees then we move apply (1, 0) to move the left motor forward 100% and the right motor stays still. The 8 points shown above are pretty easy. For the points in between those 8 we do some math to figure out what the percentages should be. Take 11.25 degrees for example. We look at how the motors transition from 0 degrees to 45 degrees: - the left motor is 1 so that is easy - the right motor moves from -1 to 0 We determine how far we are between 0 and 45 degrees (11.25 is 25% of 45) so we know that the right motor should be 25% of the way from -1 to 0...so -0.75 is the percentage for the right motor at 11.25 degrees.
def angle_to_speed_percentage(angle): """ The following graphic illustrates the **motor power outputs** for the left and right motors based on where the joystick is pointing, of the form ``(left power, right power)``:: (1, 1) . . . . . . . . | . . | . (0, 1) . | . (1, 0) . | . . | . . | . . | . . | . . | x-axis . (-1, 1) .---------------------------------------. (1, -1) . | . . | . . | . . | y-axis . . | . (0, -1) . | . (-1, 0) . | . . | . . . . . . . . (-1, -1) The joystick is a circle within a circle where the (x, y) coordinates of the joystick form an angle with the x-axis. Our job is to translate this angle into the percentage of power that should be sent to each motor. For instance if the joystick is moved all the way to the top of the circle we want both motors to move forward with 100% power...that is represented above by (1, 1). If the joystick is moved all the way to the right side of the circle we want to rotate clockwise so we move the left motor forward 100% and the right motor backwards 100%...so (1, -1). If the joystick is at 45 degrees then we move apply (1, 0) to move the left motor forward 100% and the right motor stays still. The 8 points shown above are pretty easy. For the points in between those 8 we do some math to figure out what the percentages should be. Take 11.25 degrees for example. We look at how the motors transition from 0 degrees to 45 degrees: - the left motor is 1 so that is easy - the right motor moves from -1 to 0 We determine how far we are between 0 and 45 degrees (11.25 is 25% of 45) so we know that the right motor should be 25% of the way from -1 to 0...so -0.75 is the percentage for the right motor at 11.25 degrees. """ if 0 <= angle <= 45: # left motor stays at 1 left_speed_percentage = 1 # right motor transitions from -1 to 0 right_speed_percentage = -1 + (angle/45.0) elif 45 < angle <= 90: # left motor stays at 1 left_speed_percentage = 1 # right motor transitions from 0 to 1 percentage_from_45_to_90 = (angle - 45) / 45.0 right_speed_percentage = percentage_from_45_to_90 elif 90 < angle <= 135: # left motor transitions from 1 to 0 percentage_from_90_to_135 = (angle - 90) / 45.0 left_speed_percentage = 1 - percentage_from_90_to_135 # right motor stays at 1 right_speed_percentage = 1 elif 135 < angle <= 180: # left motor transitions from 0 to -1 percentage_from_135_to_180 = (angle - 135) / 45.0 left_speed_percentage = -1 * percentage_from_135_to_180 # right motor stays at 1 right_speed_percentage = 1 elif 180 < angle <= 225: # left motor transitions from -1 to 0 percentage_from_180_to_225 = (angle - 180) / 45.0 left_speed_percentage = -1 + percentage_from_180_to_225 # right motor transitions from 1 to -1 # right motor transitions from 1 to 0 between 180 and 202.5 if angle < 202.5: percentage_from_180_to_202 = (angle - 180) / 22.5 right_speed_percentage = 1 - percentage_from_180_to_202 # right motor is 0 at 202.5 elif angle == 202.5: right_speed_percentage = 0 # right motor transitions from 0 to -1 between 202.5 and 225 else: percentage_from_202_to_225 = (angle - 202.5) / 22.5 right_speed_percentage = -1 * percentage_from_202_to_225 elif 225 < angle <= 270: # left motor transitions from 0 to -1 percentage_from_225_to_270 = (angle - 225) / 45.0 left_speed_percentage = -1 * percentage_from_225_to_270 # right motor stays at -1 right_speed_percentage = -1 elif 270 < angle <= 315: # left motor stays at -1 left_speed_percentage = -1 # right motor transitions from -1 to 0 percentage_from_270_to_315 = (angle - 270) / 45.0 right_speed_percentage = -1 + percentage_from_270_to_315 elif 315 < angle <= 360: # left motor transitions from -1 to 1 # left motor transitions from -1 to 0 between 315 and 337.5 if angle < 337.5: percentage_from_315_to_337 = (angle - 315) / 22.5 left_speed_percentage = (1 - percentage_from_315_to_337) * -1 # left motor is 0 at 337.5 elif angle == 337.5: left_speed_percentage = 0 # left motor transitions from 0 to 1 between 337.5 and 360 elif angle > 337.5: percentage_from_337_to_360 = (angle - 337.5) / 22.5 left_speed_percentage = percentage_from_337_to_360 # right motor transitions from 0 to -1 percentage_from_315_to_360 = (angle - 315) / 45.0 right_speed_percentage = -1 * percentage_from_315_to_360 else: raise Exception('You created a circle with more than 360 degrees ({})...that is quite the trick'.format(angle)) return (left_speed_percentage * 100, right_speed_percentage * 100)
Given a datetime.timedelta object, return the delta in milliseconds
def datetime_delta_to_ms(delta): """ Given a datetime.timedelta object, return the delta in milliseconds """ delta_ms = delta.days * 24 * 60 * 60 * 1000 delta_ms += delta.seconds * 1000 delta_ms += delta.microseconds / 1000 delta_ms = int(delta_ms) return delta_ms
Returns the maximum allowable brightness value.
def max_brightness(self): """ Returns the maximum allowable brightness value. """ self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness') return value
Return True if ``duration_seconds`` have expired since ``start_time``
def duration_expired(start_time, duration_seconds): """ Return True if ``duration_seconds`` have expired since ``start_time`` """ if duration_seconds is not None: delta_seconds = datetime_delta_to_seconds(dt.datetime.now() - start_time) if delta_seconds >= duration_seconds: return True return False
Sets the brightness level. Possible values are from 0 to `max_brightness`.
def brightness(self): """ Sets the brightness level. Possible values are from 0 to `max_brightness`. """ self._brightness, value = self.get_attr_int(self._brightness, 'brightness') return value
Returns a list of available triggers.
def triggers(self): """ Returns a list of available triggers. """ self._triggers, value = self.get_attr_set(self._triggers, 'trigger') return value
Sets the LED trigger. A trigger is a kernel based source of LED events. Triggers can either be simple or complex. A simple trigger isn't configurable and is designed to slot into existing subsystems with minimal additional code. Examples are the `ide-disk` and `nand-disk` triggers. Complex triggers whilst available to all LEDs have LED specific parameters and work on a per LED basis. The `timer` trigger is an example. The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` and `off` time can be specified via `delay_{on,off}` attributes in milliseconds. You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to 0 it will also disable the `timer` trigger.
def trigger(self): """ Sets the LED trigger. A trigger is a kernel based source of LED events. Triggers can either be simple or complex. A simple trigger isn't configurable and is designed to slot into existing subsystems with minimal additional code. Examples are the `ide-disk` and `nand-disk` triggers. Complex triggers whilst available to all LEDs have LED specific parameters and work on a per LED basis. The `timer` trigger is an example. The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` and `off` time can be specified via `delay_{on,off}` attributes in milliseconds. You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to 0 it will also disable the `timer` trigger. """ self._trigger, value = self.get_attr_from_set(self._trigger, 'trigger') return value
The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` time can be specified via `delay_on` attribute in milliseconds.
def delay_on(self): """ The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `on` time can be specified via `delay_on` attribute in milliseconds. """ # Workaround for ev3dev/ev3dev#225. # 'delay_on' and 'delay_off' attributes are created when trigger is set # to 'timer', and destroyed when it is set to anything else. # This means the file cache may become outdated, and we may have to # reopen the file. for retry in (True, False): try: self._delay_on, value = self.get_attr_int(self._delay_on, 'delay_on') return value except OSError: if retry: self._delay_on = None else: raise
The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `off` time can be specified via `delay_off` attribute in milliseconds.
def delay_off(self): """ The `timer` trigger will periodically change the LED brightness between 0 and the current brightness setting. The `off` time can be specified via `delay_off` attribute in milliseconds. """ # Workaround for ev3dev/ev3dev#225. # 'delay_on' and 'delay_off' attributes are created when trigger is set # to 'timer', and destroyed when it is set to anything else. # This means the file cache may become outdated, and we may have to # reopen the file. for retry in (True, False): try: self._delay_off, value = self.get_attr_int(self._delay_off, 'delay_off') return value except OSError: if retry: self._delay_off = None else: raise
Sets brightness of LEDs in the given group to the values specified in color tuple. When percentage is specified, brightness of each LED is reduced proportionally. Example:: my_leds = Leds() my_leds.set_color('LEFT', 'AMBER') With a custom color:: my_leds = Leds() my_leds.set_color('LEFT', (0.5, 0.3))
def set_color(self, group, color, pct=1): """ Sets brightness of LEDs in the given group to the values specified in color tuple. When percentage is specified, brightness of each LED is reduced proportionally. Example:: my_leds = Leds() my_leds.set_color('LEFT', 'AMBER') With a custom color:: my_leds = Leds() my_leds.set_color('LEFT', (0.5, 0.3)) """ # If this is a platform without LEDs there is nothing to do if not self.leds: return color_tuple = color if isinstance(color, str): assert color in self.led_colors, \ "%s is an invalid LED color, valid choices are %s" % \ (color, ', '.join(self.led_colors.keys())) color_tuple = self.led_colors[color] assert group in self.led_groups, \ "%s is an invalid LED group, valid choices are %s" % \ (group, ', '.join(self.led_groups.keys())) for led, value in zip(self.led_groups[group], color_tuple): led.brightness_pct = value * pct
Set attributes for each LED in group. Example:: my_leds = Leds() my_leds.set_color('LEFT', brightness_pct=0.5, trigger='timer')
def set(self, group, **kwargs): """ Set attributes for each LED in group. Example:: my_leds = Leds() my_leds.set_color('LEFT', brightness_pct=0.5, trigger='timer') """ # If this is a platform without LEDs there is nothing to do if not self.leds: return assert group in self.led_groups, \ "%s is an invalid LED group, valid choices are %s" % \ (group, ', '.join(self.led_groups.keys())) for led in self.led_groups[group]: for k in kwargs: setattr(led, k, kwargs[k])
Turn all LEDs off
def all_off(self): """ Turn all LEDs off """ # If this is a platform without LEDs there is nothing to do if not self.leds: return for led in self.leds.values(): led.brightness = 0
Put all LEDs back to their default color
def reset(self): """ Put all LEDs back to their default color """ if not self.leds: return self.animate_stop() for group in self.led_groups: self.set_color(group, LED_DEFAULT_COLOR)
Cycle the ``group1`` and ``group2`` LEDs between ``color1`` and ``color2`` to give the effect of police lights. Alternate the ``group1`` and ``group2`` LEDs every ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_police_lights('RED', 'GREEN', sleeptime=0.75, duration=10)
def animate_police_lights(self, color1, color2, group1='LEFT', group2='RIGHT', sleeptime=0.5, duration=5, block=True): """ Cycle the ``group1`` and ``group2`` LEDs between ``color1`` and ``color2`` to give the effect of police lights. Alternate the ``group1`` and ``group2`` LEDs every ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_police_lights('RED', 'GREEN', sleeptime=0.75, duration=10) """ def _animate_police_lights(): self.all_off() even = True start_time = dt.datetime.now() while True: if even: self.set_color(group1, color1) self.set_color(group2, color2) else: self.set_color(group1, color2) self.set_color(group2, color1) if self.animate_thread_stop or duration_expired(start_time, duration): break even = not even sleep(sleeptime) self.animate_thread_stop = False self.animate_thread_id = None self.animate_stop() if block: _animate_police_lights() else: self.animate_thread_id = _thread.start_new_thread(_animate_police_lights, ())
Turn all LEDs in ``groups`` off/on to ``color`` every ``sleeptime`` seconds Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_flash('AMBER', sleeptime=0.75, duration=10)
def animate_flash(self, color, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True): """ Turn all LEDs in ``groups`` off/on to ``color`` every ``sleeptime`` seconds Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_flash('AMBER', sleeptime=0.75, duration=10) """ def _animate_flash(): even = True start_time = dt.datetime.now() while True: if even: for group in groups: self.set_color(group, color) else: self.all_off() if self.animate_thread_stop or duration_expired(start_time, duration): break even = not even sleep(sleeptime) self.animate_thread_stop = False self.animate_thread_id = None self.animate_stop() if block: _animate_flash() else: self.animate_thread_id = _thread.start_new_thread(_animate_flash, ())
Cycle ``groups`` LEDs through ``colors``. Do this in a loop where we display each color for ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_cyle(('RED', 'GREEN', 'AMBER'))
def animate_cycle(self, colors, groups=('LEFT', 'RIGHT'), sleeptime=0.5, duration=5, block=True): """ Cycle ``groups`` LEDs through ``colors``. Do this in a loop where we display each color for ``sleeptime`` seconds. Animate for ``duration`` seconds. If ``duration`` is None animate for forever. Example: .. code-block:: python from ev3dev2.led import Leds leds = Leds() leds.animate_cyle(('RED', 'GREEN', 'AMBER')) """ def _animate_cycle(): index = 0 max_index = len(colors) start_time = dt.datetime.now() while True: for group in groups: self.set_color(group, colors[index]) index += 1 if index == max_index: index = 0 if self.animate_thread_stop or duration_expired(start_time, duration): break sleep(sleeptime) self.animate_thread_stop = False self.animate_thread_id = None self.animate_stop() if block: _animate_cycle() else: self.animate_thread_id = _thread.start_new_thread(_animate_cycle, ())
If the request is for a known file type serve the file (or send a 404) and return True
def do_GET(self): """ If the request is for a known file type serve the file (or send a 404) and return True """ if self.path == "/": self.path = "/index.html" # Serve a file (image, css, html, etc) if '.' in self.path: extension = self.path.split('.')[-1] mt = self.mimetype.get(extension) if mt: filename = os.curdir + os.sep + self.path # Open the static file requested and send it if os.path.exists(filename): self.send_response(200) self.send_header('Content-type', mt) self.end_headers() if extension in ('gif', 'ico', 'jpg', 'png'): # Open in binary mode, do not encode with open(filename, mode='rb') as fh: self.wfile.write(fh.read()) else: # Open as plain text and encode with open(filename, mode='r') as fh: self.wfile.write(fh.read().encode()) else: log.error("404: %s not found" % self.path) self.send_error(404, 'File Not Found: %s' % self.path) return True return False
Returns True if the requested URL is supported
def do_GET(self): """ Returns True if the requested URL is supported """ if RobotWebHandler.do_GET(self): return True global motor_max_speed global medium_motor_max_speed global max_move_xy_seq global joystick_engaged if medium_motor_max_speed is None: motor_max_speed = self.robot.left_motor.max_speed if hasattr(self.robot, 'medium_motor'): medium_motor_max_speed = self.robot.medium_motor.max_speed else: medium_motor_max_speed = 0 ''' Sometimes we get AJAX requests out of order like this: 2016-09-06 02:29:35,846 DEBUG: seq 65: (x, y): 0, 44 -> speed 462 462 2016-09-06 02:29:35,910 DEBUG: seq 66: (x, y): 0, 45 -> speed 473 473 2016-09-06 02:29:35,979 DEBUG: seq 67: (x, y): 0, 46 -> speed 483 483 2016-09-06 02:29:36,033 DEBUG: seq 69: (x, y): -1, 48 -> speed 491 504 2016-09-06 02:29:36,086 DEBUG: seq 68: (x, y): -1, 47 -> speed 480 494 2016-09-06 02:29:36,137 DEBUG: seq 70: (x, y): -1, 49 -> speed 501 515 2016-09-06 02:29:36,192 DEBUG: seq 73: (x, y): -2, 51 -> speed 509 536 2016-09-06 02:29:36,564 DEBUG: seq 74: (x, y): -3, 51 -> speed 496 536 2016-09-06 02:29:36,649 INFO: seq 75: CLIENT LOG: touchend 2016-09-06 02:29:36,701 DEBUG: seq 71: (x, y): -1, 50 -> speed 512 525 2016-09-06 02:29:36,760 DEBUG: seq 76: move stop 2016-09-06 02:29:36,814 DEBUG: seq 72: (x, y): -1, 51 -> speed 522 536 This can be bad because the last command sequentially was #76 which was "move stop" but we RXed seq #72 after that so we started moving again and never stopped A quick fix is to have the client send us an AJAX request to let us know when the joystick has been engaged so that we can ignore any move-xy events that we get out of order and show up after "move stop" but before the next "joystick-engaged" We can also ignore any move-xy requests that show up late by tracking the max seq for any move-xy we service. ''' path = self.path.split('/') seq = int(path[1]) action = path[2] # desktop interface if action == 'move-start': direction = path[3] speed_percentage = path[4] log.debug("seq %d: move %s" % (seq, direction)) left_speed = int(int(speed_percentage) * motor_max_speed)/100.0 right_speed = int(int(speed_percentage) * motor_max_speed)/100.0 if direction == 'forward': self.robot.left_motor.run_forever(speed_sp=left_speed) self.robot.right_motor.run_forever(speed_sp=right_speed) elif direction == 'backward': self.robot.left_motor.run_forever(speed_sp=left_speed * -1) self.robot.right_motor.run_forever(speed_sp=right_speed * -1) elif direction == 'left': self.robot.left_motor.run_forever(speed_sp=left_speed * -1) self.robot.right_motor.run_forever(speed_sp=right_speed) elif direction == 'right': self.robot.left_motor.run_forever(speed_sp=left_speed) self.robot.right_motor.run_forever(speed_sp=right_speed * -1) # desktop & mobile interface elif action == 'move-stop': log.debug("seq %d: move stop" % seq) self.robot.left_motor.stop() self.robot.right_motor.stop() joystick_engaged = False # medium motor elif action == 'motor-stop': motor = path[3] log.debug("seq %d: motor-stop %s" % (seq, motor)) if motor == 'medium': if hasattr(self.robot, 'medium_motor'): self.robot.medium_motor.stop() else: raise Exception("motor %s not supported yet" % motor) elif action == 'motor-start': motor = path[3] direction = path[4] speed_percentage = path[5] log.debug("seq %d: start motor %s, direction %s, speed_percentage %s" % (seq, motor, direction, speed_percentage)) if motor == 'medium': if hasattr(self.robot, 'medium_motor'): if direction == 'clockwise': medium_speed = int(int(speed_percentage) * medium_motor_max_speed)/100.0 self.robot.medium_motor.run_forever(speed_sp=medium_speed) elif direction == 'counter-clockwise': medium_speed = int(int(speed_percentage) * medium_motor_max_speed)/100.0 self.robot.medium_motor.run_forever(speed_sp=medium_speed * -1) else: log.info("we do not have a medium_motor") else: raise Exception("motor %s not supported yet" % motor) # mobile interface elif action == 'move-xy': x = int(path[3]) y = int(path[4]) if joystick_engaged: if seq > max_move_xy_seq: self.robot.on(x, y) max_move_xy_seq = seq log.debug("seq %d: (x, y) (%4d, %4d)" % (seq, x, y)) else: log.debug("seq %d: (x, y) %4d, %4d (ignore, max seq %d)" % (seq, x, y, max_move_xy_seq)) else: log.debug("seq %d: (x, y) %4d, %4d (ignore, joystick idle)" % (seq, x, y)) elif action == 'joystick-engaged': joystick_engaged = True elif action == 'log': msg = ''.join(path[3:]) re_msg = re.search('^(.*)\?', msg) if re_msg: msg = re_msg.group(1) log.debug("seq %d: CLIENT LOG: %s" % (seq, msg)) else: log.warning("Unsupported URL %s" % self.path) # It is good practice to send this but if we are getting move-xy we # tend to get a lot of them and we need to be as fast as possible so # be bad and don't send a reply. This takes ~20ms. if action != 'move-xy': self.send_response(204) return True
Red, green, and blue components of the detected color, as a tuple. Officially in the range 0-1020 but the values returned will never be that high. We do not yet know why the values returned are low, but pointing the color sensor at a well lit sheet of white paper will return values in the 250-400 range. If this is an issue, check out the rgb() and calibrate_white() methods.
def raw(self): """ Red, green, and blue components of the detected color, as a tuple. Officially in the range 0-1020 but the values returned will never be that high. We do not yet know why the values returned are low, but pointing the color sensor at a well lit sheet of white paper will return values in the 250-400 range. If this is an issue, check out the rgb() and calibrate_white() methods. """ self._ensure_mode(self.MODE_RGB_RAW) return self.value(0), self.value(1), self.value(2)
The RGB raw values are on a scale of 0-1020 but you never see a value anywhere close to 1020. This function is designed to be called when the sensor is placed over a white object in order to figure out what are the maximum RGB values the robot can expect to see. We will use these maximum values to scale future raw values to a 0-255 range in rgb(). If you never call this function red_max, green_max, and blue_max will use a default value of 300. This default was selected by measuring the RGB values of a white sheet of paper in a well lit room. Note that there are several variables that influence the maximum RGB values detected by the color sensor - the distance of the color sensor to the white object - the amount of light in the room - shadows that the robot casts on the sensor
def calibrate_white(self): """ The RGB raw values are on a scale of 0-1020 but you never see a value anywhere close to 1020. This function is designed to be called when the sensor is placed over a white object in order to figure out what are the maximum RGB values the robot can expect to see. We will use these maximum values to scale future raw values to a 0-255 range in rgb(). If you never call this function red_max, green_max, and blue_max will use a default value of 300. This default was selected by measuring the RGB values of a white sheet of paper in a well lit room. Note that there are several variables that influence the maximum RGB values detected by the color sensor - the distance of the color sensor to the white object - the amount of light in the room - shadows that the robot casts on the sensor """ (self.red_max, self.green_max, self.blue_max) = self.raw
Same as raw() but RGB values are scaled to 0-255
def rgb(self): """ Same as raw() but RGB values are scaled to 0-255 """ (red, green, blue) = self.raw return (min(int((red * 255) / self.red_max), 255), min(int((green * 255) / self.green_max), 255), min(int((blue * 255) / self.blue_max), 255))
Return colors in Lab color space
def lab(self): """ Return colors in Lab color space """ RGB = [0, 0, 0] XYZ = [0, 0, 0] for (num, value) in enumerate(self.rgb): if value > 0.04045: value = pow(((value + 0.055) / 1.055), 2.4) else: value = value / 12.92 RGB[num] = value * 100.0 # http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html # sRGB # 0.4124564 0.3575761 0.1804375 # 0.2126729 0.7151522 0.0721750 # 0.0193339 0.1191920 0.9503041 X = (RGB[0] * 0.4124564) + (RGB[1] * 0.3575761) + (RGB[2] * 0.1804375) Y = (RGB[0] * 0.2126729) + (RGB[1] * 0.7151522) + (RGB[2] * 0.0721750) Z = (RGB[0] * 0.0193339) + (RGB[1] * 0.1191920) + (RGB[2] * 0.9503041) XYZ[0] = X / 95.047 # ref_X = 95.047 XYZ[1] = Y / 100.0 # ref_Y = 100.000 XYZ[2] = Z / 108.883 # ref_Z = 108.883 for (num, value) in enumerate(XYZ): if value > 0.008856: value = pow(value, (1.0 / 3.0)) else: value = (7.787 * value) + (16 / 116.0) XYZ[num] = value L = (116.0 * XYZ[1]) - 16 a = 500.0 * (XYZ[0] - XYZ[1]) b = 200.0 * (XYZ[1] - XYZ[2]) L = round(L, 4) a = round(a, 4) b = round(b, 4) return (L, a, b)
HSV: Hue, Saturation, Value H: position in the spectrum S: color saturation ("purity") V: color brightness
def hsv(self): """ HSV: Hue, Saturation, Value H: position in the spectrum S: color saturation ("purity") V: color brightness """ (r, g, b) = self.rgb maxc = max(r, g, b) minc = min(r, g, b) v = maxc if minc == maxc: return 0.0, 0.0, v s = (maxc-minc) / maxc rc = (maxc-r) / (maxc-minc) gc = (maxc-g) / (maxc-minc) bc = (maxc-b) / (maxc-minc) if r == maxc: h = bc-gc elif g == maxc: h = 2.0+rc-bc else: h = 4.0+gc-rc h = (h/6.0) % 1.0 return (h, s, v)
HLS: Hue, Luminance, Saturation H: position in the spectrum L: color lightness S: color saturation
def hls(self): """ HLS: Hue, Luminance, Saturation H: position in the spectrum L: color lightness S: color saturation """ (r, g, b) = self.rgb maxc = max(r, g, b) minc = min(r, g, b) l = (minc+maxc)/2.0 if minc == maxc: return 0.0, l, 0.0 if l <= 0.5: s = (maxc-minc) / (maxc+minc) else: if 2.0-maxc-minc == 0: s = 0 else: s = (maxc-minc) / (2.0-maxc-minc) rc = (maxc-r) / (maxc-minc) gc = (maxc-g) / (maxc-minc) bc = (maxc-b) / (maxc-minc) if r == maxc: h = bc-gc elif g == maxc: h = 2.0+rc-bc else: h = 4.0+gc-rc h = (h/6.0) % 1.0 return (h, l, s)
Measurement of the distance detected by the sensor, in centimeters. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimeters` property.
def distance_centimeters_continuous(self): """ Measurement of the distance detected by the sensor, in centimeters. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimeters` property. """ self._ensure_mode(self.MODE_US_DIST_CM) return self.value(0) * self._scale('US_DIST_CM')
Measurement of the distance detected by the sensor, in centimeters. The sensor will take a single measurement then stop broadcasting. If you use this property too frequently (e.g. every 100msec), the sensor will sometimes lock up and writing to the mode attribute will return an error. A delay of 250msec between each usage seems sufficient to keep the sensor from locking up.
def distance_centimeters_ping(self): """ Measurement of the distance detected by the sensor, in centimeters. The sensor will take a single measurement then stop broadcasting. If you use this property too frequently (e.g. every 100msec), the sensor will sometimes lock up and writing to the mode attribute will return an error. A delay of 250msec between each usage seems sufficient to keep the sensor from locking up. """ # This mode is special; setting the mode causes the sensor to send out # a "ping", but the mode isn't actually changed. self.mode = self.MODE_US_SI_CM return self.value(0) * self._scale('US_DIST_CM')
Measurement of the distance detected by the sensor, in inches. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_inches` property.
def distance_inches_continuous(self): """ Measurement of the distance detected by the sensor, in inches. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_inches` property. """ self._ensure_mode(self.MODE_US_DIST_IN) return self.value(0) * self._scale('US_DIST_IN')
Measurement of the distance detected by the sensor, in inches. The sensor will take a single measurement then stop broadcasting. If you use this property too frequently (e.g. every 100msec), the sensor will sometimes lock up and writing to the mode attribute will return an error. A delay of 250msec between each usage seems sufficient to keep the sensor from locking up.
def distance_inches_ping(self): """ Measurement of the distance detected by the sensor, in inches. The sensor will take a single measurement then stop broadcasting. If you use this property too frequently (e.g. every 100msec), the sensor will sometimes lock up and writing to the mode attribute will return an error. A delay of 250msec between each usage seems sufficient to keep the sensor from locking up. """ # This mode is special; setting the mode causes the sensor to send out # a "ping", but the mode isn't actually changed. self.mode = self.MODE_US_SI_IN return self.value(0) * self._scale('US_DIST_IN')
Angle (degrees) and Rotational Speed (degrees/second).
def angle_and_rate(self): """ Angle (degrees) and Rotational Speed (degrees/second). """ self._ensure_mode(self.MODE_GYRO_G_A) return self.value(0), self.value(1)
Wait until angle has changed by specified amount. If ``direction_sensitive`` is True we will wait until angle has changed by ``delta`` and with the correct sign. If ``direction_sensitive`` is False (default) we will wait until angle has changed by ``delta`` in either direction.
def wait_until_angle_changed_by(self, delta, direction_sensitive=False): """ Wait until angle has changed by specified amount. If ``direction_sensitive`` is True we will wait until angle has changed by ``delta`` and with the correct sign. If ``direction_sensitive`` is False (default) we will wait until angle has changed by ``delta`` in either direction. """ assert self.mode in (self.MODE_GYRO_G_A, self.MODE_GYRO_ANG, self.MODE_TILT_ANG),\ 'Gyro mode should be MODE_GYRO_ANG, MODE_GYRO_G_A or MODE_TILT_ANG' start_angle = self.value(0) if direction_sensitive: if delta > 0: while (self.value(0) - start_angle) < delta: time.sleep(0.01) else: delta *= -1 while (start_angle - self.value(0)) < delta: time.sleep(0.01) else: while abs(start_angle - self.value(0)) < delta: time.sleep(0.01)
Returns heading (-25, 25) to the beacon on the given channel.
def heading(self, channel=1): """ Returns heading (-25, 25) to the beacon on the given channel. """ self._ensure_mode(self.MODE_IR_SEEK) channel = self._normalize_channel(channel) return self.value(channel * 2)
Returns distance (0, 100) to the beacon on the given channel. Returns None when beacon is not found.
def distance(self, channel=1): """ Returns distance (0, 100) to the beacon on the given channel. Returns None when beacon is not found. """ self._ensure_mode(self.MODE_IR_SEEK) channel = self._normalize_channel(channel) ret_value = self.value((channel * 2) + 1) # The value will be -128 if no beacon is found, return None instead return None if ret_value == -128 else ret_value
Returns list of currently pressed buttons. Note that the sensor can only identify up to two buttons pressed at once.
def buttons_pressed(self, channel=1): """ Returns list of currently pressed buttons. Note that the sensor can only identify up to two buttons pressed at once. """ self._ensure_mode(self.MODE_IR_REMOTE) channel = self._normalize_channel(channel) return self._BUTTON_VALUES.get(self.value(channel), [])
Check for currenly pressed buttons. If the new state differs from the old state, call the appropriate button event handlers. To use the on_channel1_top_left, etc handlers your program would do something like: .. code:: python def top_left_channel_1_action(state): print("top left on channel 1: %s" % state) def bottom_right_channel_4_action(state): print("bottom right on channel 4: %s" % state) ir = InfraredSensor() ir.on_channel1_top_left = top_left_channel_1_action ir.on_channel4_bottom_right = bottom_right_channel_4_action while True: ir.process() time.sleep(0.01)
def process(self): """ Check for currenly pressed buttons. If the new state differs from the old state, call the appropriate button event handlers. To use the on_channel1_top_left, etc handlers your program would do something like: .. code:: python def top_left_channel_1_action(state): print("top left on channel 1: %s" % state) def bottom_right_channel_4_action(state): print("bottom right on channel 4: %s" % state) ir = InfraredSensor() ir.on_channel1_top_left = top_left_channel_1_action ir.on_channel4_bottom_right = bottom_right_channel_4_action while True: ir.process() time.sleep(0.01) """ new_state = [] state_diff = [] for channel in range(1,5): for button in self.buttons_pressed(channel): new_state.append((button, channel)) # Key was not pressed before but now is pressed if (button, channel) not in self._state: state_diff.append((button, channel)) # Key was pressed but is no longer pressed for button in self._BUTTONS: if (button, channel) not in new_state and (button, channel) in self._state: state_diff.append((button, channel)) old_state = self._state self._state = new_state for (button, channel) in state_diff: handler = getattr(self, 'on_channel' + str(channel) + '_' + button ) if handler is not None: handler((button, channel) in new_state) if self.on_change is not None and state_diff: self.on_change([(button, channel, button in new_state) for (button, channel) in state_diff])
A measurement of the measured sound pressure level, as a percent. Uses a flat weighting.
def sound_pressure(self): """ A measurement of the measured sound pressure level, as a percent. Uses a flat weighting. """ self._ensure_mode(self.MODE_DB) return self.value(0) * self._scale('DB')
A measurement of the measured sound pressure level, as a percent. Uses A-weighting, which focuses on levels up to 55 dB.
def sound_pressure_low(self): """ A measurement of the measured sound pressure level, as a percent. Uses A-weighting, which focuses on levels up to 55 dB. """ self._ensure_mode(self.MODE_DBA) return self.value(0) * self._scale('DBA')
A measurement of the reflected light intensity, as a percentage.
def reflected_light_intensity(self): """ A measurement of the reflected light intensity, as a percentage. """ self._ensure_mode(self.MODE_REFLECT) return self.value(0) * self._scale('REFLECT')
A measurement of the ambient light intensity, as a percentage.
def ambient_light_intensity(self): """ A measurement of the ambient light intensity, as a percentage. """ self._ensure_mode(self.MODE_AMBIENT) return self.value(0) * self._scale('AMBIENT')
The measured current that the battery is supplying (in microamps)
def measured_current(self): """ The measured current that the battery is supplying (in microamps) """ self._measured_current, value = self.get_attr_int(self._measured_current, 'current_now') return value
The measured voltage that the battery is supplying (in microvolts)
def measured_voltage(self): """ The measured voltage that the battery is supplying (in microvolts) """ self._measured_voltage, value = self.get_attr_int(self._measured_voltage, 'voltage_now') return value
Returns list of available font names.
def available(): """ Returns list of available font names. """ font_dir = os.path.dirname(__file__) names = [os.path.basename(os.path.splitext(f)[0]) for f in glob(os.path.join(font_dir, '*.pil'))] return sorted(names)
Loads the font specified by name and returns it as an instance of `PIL.ImageFont <http://pillow.readthedocs.io/en/latest/reference/ImageFont.html>`_ class.
def load(name): """ Loads the font specified by name and returns it as an instance of `PIL.ImageFont <http://pillow.readthedocs.io/en/latest/reference/ImageFont.html>`_ class. """ try: font_dir = os.path.dirname(__file__) pil_file = os.path.join(font_dir, '{}.pil'.format(name)) pbm_file = os.path.join(font_dir, '{}.pbm'.format(name)) return ImageFont.load(pil_file) except FileNotFoundError: raise Exception('Failed to load font "{}". '.format(name) + 'Check ev3dev.fonts.available() for the list of available fonts')
Returns a list of the available modes of the port.
def modes(self): """ Returns a list of the available modes of the port. """ (self._modes, value) = self.get_cached_attr_set(self._modes, 'modes') return value
Reading returns the currently selected mode. Writing sets the mode. Generally speaking when the mode changes any sensor or motor devices associated with the port will be removed new ones loaded, however this this will depend on the individual driver implementing this class.
def mode(self): """ Reading returns the currently selected mode. Writing sets the mode. Generally speaking when the mode changes any sensor or motor devices associated with the port will be removed new ones loaded, however this this will depend on the individual driver implementing this class. """ self._mode, value = self.get_attr_string(self._mode, 'mode') return value
In most cases, reading status will return the same value as `mode`. In cases where there is an `auto` mode additional values may be returned, such as `no-device` or `error`. See individual port driver documentation for the full list of possible values.
def status(self): """ In most cases, reading status will return the same value as `mode`. In cases where there is an `auto` mode additional values may be returned, such as `no-device` or `error`. See individual port driver documentation for the full list of possible values. """ self._status, value = self.get_attr_string(self._status, 'status') return value
This is a generator function that enumerates all sensors that match the provided arguments. Parameters: name_pattern: pattern that device name should match. For example, 'sensor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, driver_name='lego-ev3-touch', or address=['in1', 'in3']. When argument value is a list, then a match against any entry of the list is enough.
def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs): """ This is a generator function that enumerates all sensors that match the provided arguments. Parameters: name_pattern: pattern that device name should match. For example, 'sensor*'. Default value: '*'. keyword arguments: used for matching the corresponding device attributes. For example, driver_name='lego-ev3-touch', or address=['in1', 'in3']. When argument value is a list, then a match against any entry of the list is enough. """ class_path = abspath(Device.DEVICE_ROOT_PATH + '/' + Sensor.SYSTEM_CLASS_NAME) return (Sensor(name_pattern=name, name_exact=True) for name in list_device_names(class_path, name_pattern, **kwargs))
Returns value scaling coefficient for the given mode.
def _scale(self, mode): """ Returns value scaling coefficient for the given mode. """ if mode in self._mode_scale: scale = self._mode_scale[mode] else: scale = 10**(-self.decimals) self._mode_scale[mode] = scale return scale
Returns the number of decimal places for the values in the `value<N>` attributes of the current mode.
def decimals(self): """ Returns the number of decimal places for the values in the `value<N>` attributes of the current mode. """ self._decimals, value = self.get_attr_int(self._decimals, 'decimals') return value
Returns the number of `value<N>` attributes that will return a valid value for the current mode.
def num_values(self): """ Returns the number of `value<N>` attributes that will return a valid value for the current mode. """ self._num_values, value = self.get_attr_int(self._num_values, 'num_values') return value