예제 #1
0
class WalkDog:
    def __init__(self, left_motor_port, right_motor_port, sensor_mode):
        self._movesteering = MoveSteering(left_motor_port, right_motor_port)
        self._ir = InfraredSensor()
        self._ir.mode = sensor_mode

    @property
    def ir(self):
        return self._ir

    @ir.setter
    def ir(self, ir):
        self._ir = ir

    @property
    def movesteering(self):
        return _movesteering

    @movesteering.setter
    def movesteering(self, ms):
        self._movesteering = ms

    def convert_heading_to_steering(self, heading):
        return heading * 2

    def run(self, channel=1):
        beacon_distance = self._ir.distance(channel)
        head_angle = self._ir.heading(channel)
        steering = self.convert_heading_to_steering(head_angle)
        if (beacon_distance > 30):
            self._movesteering.on(steering, 50)
        else:
            self._movesteering.off()
예제 #2
0
def main():
    '''The main function of our program'''

    # set the console just how we want it
    reset_console()
    set_cursor(OFF)
    set_font('Lat15-Terminus24x12')

    print('How are you?')
    print("")
    print("Hello Selina.")
    print("Hello Ethan.")
    STUD_MM = 8
    tank = MoveDifferential(OUTPUT_A, OUTPUT_B, EV3Tire, 16 * STUD_MM)
    motorLift = MediumMotor(OUTPUT_D)
    sound = Sound()

    # sound.speak('How are you master!')
   # sound.speak("I like my family")
   # sound.speak("I like my sister and i like my brother.")
    sound.beep()

    eye = InfraredSensor(INPUT_1)
    robot = Robot(tank, None, eye)
    botton = Button()
    while not botton.any():
        distance = eye.distance(channel=1)
        heading = eye.heading(channel=1)
        print('distance: {}, heading: {}'.format(distance, heading))

        motorLift.on_to_position(speed=40, position=-7200, block=True)  #20 Rounds

        if distance is None:
            sound.speak("I am lost, there is no beacon!")
        else:
            if (distance < 14):
                tank.off()
                sound.speak("I am very close to the beacon!")
                motorLift.on_to_position(speed=40, position=7200, block=True)
                sound.speak("I had to get some more rubbish.")
                sound.speak("Please wait while I lift up my fork.")
                tank.turn_right(speed=20, degrees=random.randint(290, 340))  # random.randint(150, 210)
                tank.on_for_seconds(left_speed=20, right_speed=20, seconds=20)
                tank.turn_right(speed=20, degrees=330)
                motorLift.on_to_position(speed=40, position=0, block=True)

            elif distance >= 100:
                sound.speak("I am too faraway from the beacon")
            elif (distance  < 99) and (-4 <= heading <= 4):  # in right heading
                sound.speak("Moving farward")
                tank.on(left_speed=20, right_speed=20)
            else:
                if heading > 0:
                    tank.turn_left(speed=20, degrees=20)
                else:
                    tank.turn_right(speed=20, degrees=20)
                sound.speak("I am finding the beacon.")


        time.sleep(0.1)
예제 #3
0
if __name__ == "__main__":
    myThread = threading.Thread(target=keyboardInput, args=(1, ), daemon=True)
    myThread.start()
    print("Ready for keyboard commands...")

    ### Main Loop
    while (True):
        usDistCmVal = us.distance_centimeters
        if usDistCmVal != prev_usDistCmVal:
            if printVerbose > 0:
                print("usDistCmVal = ", int(usDistCmVal), "  ir1DistVal = ",
                      ir1DistVal, "  compassVal = ", compassVal
                      )  # print all sensor vals, regardless of which changed
            prev_usDistCmVal = usDistCmVal

        ir1DistVal = ir.distance(channel=1)
        if ir1DistVal == None:
            ir1DistVal = -1  ### set to -1 instead of None or numpy.savetxt and other Ops will complain
        else:
            ir1DistVal = int(3.19 * ir1DistVal)
        ir1HeadVal = ir.heading(channel=1)
        if (ir1DistVal != prev_ir1DistVal):
            if printVerbose > 0:
                #print("usDistCmVal = ", int(usDistCmVal), "  ir1DistVal = ", ir1DistVal, "  ir1HeadVal = ", ir1HeadVal, "  compassVal = ", compassVal, "  mR.position = ", mR.position)  # print all sensor vals, regardless of which changed
                print("usDistCmVal = ", int(usDistCmVal), "  ir1DistVal = ",
                      ir1DistVal, "  ir1HeadVal = ", ir1HeadVal,
                      "  compassVal = ", compassVal
                      )  # print all sensor vals, regardless of which changed
            prev_ir1DistVal = ir1DistVal
            prev_ir1HeadVal = ir1HeadVal
if __name__ == "__main__":
    myThread = threading.Thread(target=keyboardInput, args=(1, ), daemon=True)
    myThread.start()
    print("Ready for keyboard commands...")

    ### Main Loop
    while (True):
        irProxVal = ir.proximity
        if irProxVal != prev_irProxVal:
            # print("irProxVal = ", irProxVal, "  irDistVal = ", irDistVal, "  irHeadVal = ", irHeadVal, "  compassVal = ", compassVal)  # print all sensor vals, regardless of which changed
            prev_irProxVal = irProxVal

        time.sleep(0.2)

        irDistVal = ir.distance()
        irHeadVal = ir.heading()
        if (irDistVal != prev_irDistVal) or (irHeadVal != prev_irHeadVal):
            # print("irProxVal = ", irProxVal, "  irDistVal = ", irDistVal, "  irHeadVal = ", irHeadVal, "  compassVal = ", compassVal)  # print all sensor vals, regardless of which changed
            prev_irDistVal = irDistVal
            prev_irHeadVal = irHeadVal
            # time.sleep(0.2)

        compassVal = cmp.value(0)
        if compassVal != prev_compassVal:
            print("irProxVal = ", irProxVal, "  irDistVal = ", irDistVal,
                  "  irHeadVal = ", irHeadVal, "  compassVal = ", compassVal
                  )  # print all sensor vals, regardless of which changed
            prev_compassVal = compassVal

        if irProxVal < 50:
class Ev3rstorm:
    def __init__(self,
                 left_foot_motor_port: str = OUTPUT_B,
                 right_foot_motor_port: str = OUTPUT_C,
                 bazooka_blast_motor_port: str = OUTPUT_A,
                 ir_sensor_port: str = INPUT_4,
                 ir_beacon_channel: int = 1):
        self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port,
                                    right_motor_port=right_foot_motor_port,
                                    motor_class=LargeMotor)

        self.bazooka_blast_motor = MediumMotor(
            address=bazooka_blast_motor_port)

        self.ir_sensor = InfraredSensor(address=ir_sensor_port)
        self.ir_beacon_channel = ir_beacon_channel

        self.leds = Leds()
        self.speaker = Sound()

    def seek_wheeler(self):
        self.leds.animate_rainbow(group1=Leds.LEFT,
                                  group2=Leds.RIGHT,
                                  increment_by=0.1,
                                  sleeptime=0.5,
                                  duration=5,
                                  block=True)

        if self.ir_sensor.beacon(channel=self.ir_beacon_channel):
            heading_difference = self.ir_sensor.heading(
                channel=self.ir_beacon_channel) - (-3)

            proximity_difference = self.ir_sensor.distance(
                channel=self.ir_beacon_channel) - 70

            if (heading_difference == 0) and (proximity_difference == 0):
                self.tank_driver.off(brake=True)

                self.leds.animate_rainbow(group1=Leds.LEFT,
                                          group2=Leds.RIGHT,
                                          increment_by=0.1,
                                          sleeptime=0.5,
                                          duration=5,
                                          block=True)

                self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                          rotations=3,
                                                          brake=True,
                                                          block=True)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Laughing 2.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                # FIXME: make it work
                self.tank_driver.on(left_speed=max(
                    min((3 * proximity_difference + 4 * heading_difference) /
                        5, 100), -100),
                                    right_speed=max(
                                        min((3 * proximity_difference -
                                             4 * heading_difference) / 5, 100),
                                        -100))

        else:
            self.tank_driver.off(brake=True)

    def main(self):
        while True:
            self.seek_wheeler()
    speed=40,
    seconds=1,
    brake=True,
    block=True)

GO_MOTOR.on(
    speed=-50,
    block=False,
    brake=False)

SPEAKER.play_file(
    wav_file='/home/robot/sound/Blip 2.wav',
    volume=100,
    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

while (INFRARED_SENSOR.distance(channel=1) is None) or (INFRARED_SENSOR.distance(channel=1) >= 30):
    pass

while INFRARED_SENSOR.heading(channel=1) <= 5:
    pass

GO_MOTOR.on(
    speed=-20,
    brake=False,
    block=False)

while INFRARED_SENSOR.heading(channel=1) >= 3:
    pass

GO_MOTOR.off(brake=True)
예제 #7
0
if __name__ == "__main__":
    myThread = threading.Thread(target=keyboardInput, args=(1,), daemon=True)
    myThread.start()
    print ("Ready for keyboard commands...")


### Main Loop
    while (True):
        usDistCmVal = us.distance_centimeters
        if usDistCmVal != prev_usDistCmVal:
            if printVerbose > 0:
                print("usDistCmVal = ", int(usDistCmVal), "  irDistVal = ", irDistVal, "  compassVal = ", compassVal)  # print all sensor vals, regardless of which changed
            prev_usDistCmVal = usDistCmVal

        irDistVal = ir.distance(channel=1)
        if irDistVal == None:
            irDistVal = -1  ### set to -1 instead of None or numpy.savetxt and other Ops will complain
        else:
            irDistVal = int(3.19 * irDistVal)
        irHeadVal = ir.heading(channel=1)
        if (irDistVal != prev_irDistVal):
            if printVerbose > 0:
                #print("usDistCmVal = ", int(usDistCmVal), "  irDistVal = ", irDistVal, "  irHeadVal = ", irHeadVal, "  compassVal = ", compassVal, "  mR.position = ", mR.position)  # print all sensor vals, regardless of which changed
                print("usDistCmVal = ", int(usDistCmVal), "  irDistVal = ", irDistVal, "  irHeadVal = ", irHeadVal, "  compassVal = ", compassVal)  # print all sensor vals, regardless of which changed
            prev_irDistVal = irDistVal
            prev_irHeadVal = irHeadVal

        compassVal = cmp.value(0)
        if compassVal != prev_compassVal:
            if printVerbose > 0:
예제 #8
0

def safe_steering(steering: float) -> float:
    if steering > 100:
        return 100
    elif steering < -100:
        return -100
    else:
        return steering


# Start program
reset()

starting = True
while starting or infrared_sensor.distance(
) == None or infrared_sensor.distance() >= 50:
    starting = False
    search()
    steering_drive.on_for_rotations(steering=0,
                                    speed=SpeedPercent(75),
                                    rotations=4)

while infrared_sensor.distance() > 2:
    steering_drive.on(steering=(safe_steering(infrared_sensor.heading() * 5)),
                      speed=SpeedPercent(50))
steering_drive.off()
sound.play_file("/home/robot/sounds/Detected.wav",
                play_type=sound.PLAY_WAIT_FOR_COMPLETE)

steering_drive.on_for_rotations(steering=0,
                                speed=SpeedPercent(50),
예제 #9
0
class MindstormsGadget(AlexaGadget):
    """
    A Mindstorms gadget that performs movement based on voice commands.
    Two types of commands are supported, directional movement and preset.
    """

    def __init__(self):
        """
        Performs Alexa Gadget initialization routines and ev3dev resource allocation.
        """
        super().__init__()

        # Gadget state
        
        self.isDoorOpen = False
        self.verified = True

        # Ev3dev initialization
        self.leds = Leds()
        self.sound = Sound()
        self.drive = MoveTank(OUTPUT_B, OUTPUT_C)
        
        self.ir_sensor = InfraredSensor()
        self.ir_sensor.mode = self.ir_sensor.MODE_IR_REMOTE
        self.color_sensor = ColorSensor()
        self.color_sensor.mode = 'COL-COLOR' # WHITE

        # Start threads
        threading.Thread(target=self._patrol_thread, daemon=True).start()

    def on_connected(self, device_addr):
        """
        Gadget connected to the paired Echo device.
        :param device_addr: the address of the device we connected to
        """
        self.leds.set_color("LEFT", "GREEN")
        self.leds.set_color("RIGHT", "GREEN")
        logger.info("{} connected to Echo device".format(self.friendly_name))

    def on_disconnected(self, device_addr):
        """
        Gadget disconnected from the paired Echo device.
        :param device_addr: the address of the device we disconnected from
        """
        self.leds.set_color("LEFT", "BLACK")
        self.leds.set_color("RIGHT", "BLACK")
        logger.info("{} disconnected from Echo device".format(self.friendly_name))

    def on_custom_mindstorms_gadget_control(self, directive):
        """
        Handles the Custom.Mindstorms.Gadget control directive.
        :param directive: the custom directive with the matching namespace and name
        """
        try:
            payload = json.loads(directive.payload.decode("utf-8"))
            logger.info("Control payload: {}".format(payload))
            control_type = payload["type"]
            
            if control_type == "open":
                self._open()

            if control_type == "close":
                self._close()

        except KeyError:
            print("Missing expected parameters: {}".format(directive), file=sys.stderr)

    

    def _activate(self, command, speed=50):
        """
        Handles preset commands.
        :param command: the preset command
        :param speed: the speed if applicable
        """
        print("Activate command: ({}, {})".format(command, speed), file=sys.stderr)
       

    def _open(self):
        if (not self.isDoorOpen) and self.verified:
            logger.info("Open door")
            self.drive.on_for_rotations(1*SpeedPercent(10), 1*SpeedPercent(10), 1.5)
            self.isDoorOpen = True
            self.color_sensor.mode = 'COL-AMBIENT' # Blue
        else:
            self.color_sensor.mode = 'COL-REFLECT' # RED

    def _close(self):
        self.color_sensor.mode = 'COL-COLOR' # WHITE

        if self.isDoorOpen:
            logger.info("Close door")
            self.drive.on_for_rotations(-1*SpeedPercent(10), -1*SpeedPercent(10), 1.5)
            self.isDoorOpen = False

    def _patrol_thread(self):
        while True:
            while not self.isDoorOpen:
                logger.info("Patrol mode activated for checking beacon")
                distance = self.ir_sensor.distance()
                logger.info("Distance: {}".format(distance))

                if distance is not None and distance < 100:
                    self.verified = True
                    logger.info("Beacon found")
                else:
                    self.verified = False
                time.sleep(1)

            time.sleep(1)
예제 #10
0
#!/usr/bin/env python3
from ev3dev2.motor import MoveSteering, OUTPUT_B, OUTPUT_C
from ev3dev2.sensor.lego import InfraredSensor
from time import sleep

steer_pair = MoveSteering(OUTPUT_B, OUTPUT_C)
ir = InfraredSensor()

while True:  # forever
    distance = ir.distance()
    if distance:  # If distance is not None
        error = distance - 10
        steer_pair.on(steering=2 * ir.heading(), speed=min(90, 3 * error))
    else:
        steer_pair.off()
    sleep(0.1)
def findPosUsingInfrared():
    BallHeading = infraredSensor.heading()
    ballDistanceInCentimeter = InfraredSensor.distance() * 0.7

    print("Lol")
예제 #12
0
sleep(2)

us = UltrasonicSensor('ev3-ports:in2:i2c80:mux1')
ir = InfraredSensor('ev3-ports:in2:i2c81:mux2')
gyro = GyroSensor('ev3-ports:in2:i2c82:mux3')

us_value = us.value(0)
us_dist = us.distance_centimeters # takes multiple measurements
us_numvalues = us.num_values
us_address = us.address
us_units = us.units

ir_value = ir.value(0)
ir_proximity = ir.proximity # an estimate of the distance between the sensor and the objects in front of it
ir_beacon= ir.distance(channel=1) # returns distance (0,100) to the beacon on the given channel
ir_heading = ir.heading(channel=1) # returns heading (-25,25) to the beacon on the given channel
ir_address = ir.address

gyro_value = gyro.value(0)
gyro_angle = gyro.angle
gyro_address = gyro.address
gyro_units = gyro.units

# Sensors connected to NXT-Sensor-Split MUX - Barometer---------------------------------------------------------

temp1 = Sensor(INPUT_1)
temp1.mode = 'TEMP'
Temp_NXT = (temp1.value(0)/1000)

pressure = Sensor(INPUT_1)