Beispiel #1
0
def run_on_color():
    color_sensor = ColorSensor(Port.S1)
    color = color_sensor.color()
    print(color)
    data.log('Color detected', color)

    rgb_value = color_sensor.rgb()
    print('Color detected RGB', rgb_value)
    data.log('Color detected RGB', rgb_value)

    ambient = color_sensor.ambient()
    print('Color detected ambient', ambient)
    data.log('Color detected ambient', ambient)

    reflection = color_sensor.reflection()
    print('Color detected reflection', reflection)
    data.log('Color detected reflection', reflection)

    #reset gyro before start of program
    gyro_sensor.reset_angle(0)

    if (color == Color.WHITE):
        ev3.speaker.say('white')
        print("Jolene Run")
        jolene_run()
        #jolene_test()
    elif (color == Color.BLUE):
        #ev3.speaker.say('blue')
        print("Jason Run")
        jason_start_slide()
    #
    #jolene_test()
    elif (color == Color.RED):
        #ev3.speaker.say('red')
        print("Sophie Run")
        sophie_run()

    elif (color == Color.BLACK):
        jason_step_counter()

    elif (color == Color.GREEN):
        sophie_bench()

    else:
        rgb_value = color_sensor.rgb()
        print(rgb_value)
        #gyro_test()
        jolene_run()
Beispiel #2
0
def displayLightValue(port):
    "Continously prints all values from color sensor at given port"

    # creat the sensor object from the ColorSensor class
    sensor = ColorSensor(port)

    while True:
        # have four different ways of using this
        # sensor!
        color = sensor.color()
        reflection = sensor.reflection()
        ambient = sensor.ambient()
        rgb = sensor.rgb()
        print("color: ", color)
        print("reflection: ", reflection)
        print("ambient: ", ambient)
        print("rgb: ", rgb)
        wait(1000)
Beispiel #3
0
class colorSensor:
    """ Defines a color sensor component. """
    def __init__(self, sensor_input):
        """
        Initializes the sensor color component.
        :param sensor_input: the input pin of the sensor
        """
        self._sensor = ColorSensor(sensor_input)

    def read_intensity(self):
        """
        Reads the reflected light intensity from the color sensor.
        :return: the intensity in [0; 100]
        """
        return self._sensor.reflection()

    def read_color(self):
        """
        Reads the color from the color sensor.
        :return: the index of the found color
        """
        return self._sensor.rgb()
Beispiel #4
0
#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile

# This program requires LEGO EV3 MicroPython v2.0 or higher.
# Click "Open user guide" on the EV3 extension tab for more information.

ev3 = EV3Brick()

# Write your program here
ev3.speaker.set_speech_options('pt-br', 'm3')

ev3.speaker.beep()

corLeft = ColorSensor(Port.S2)
corRight = ColorSensor(Port.S3)

ev3.speaker.say("Analizando cor do sensor esquerdo")

print("Sensor esquerdo=", corLeft.rgb())

ev3.speaker.say("Analizando cor do sensor direito")

print("Sensor direito =", corRight.rgb())
Beispiel #5
0
class CSensor:
    def __init__(self):

        self.sensor = ColorSensor(Port.S3)

        self.dominantColorTab = []  #List used for dominantSortingColor

        self.logColors = []  #List used to store recently found colors

    def color(self):
        """Return the color detected by the native function of the sensor"""
        return self.sensor.color()

    def rgb(self):
        """Return the sensor RGB values"""
        rgb = self.sensor.rgb()
        r = (rgb[0] / 100) * 255
        g = (rgb[1] / 100) * 255
        b = (rgb[2] / 100) * 255
        return r, g, b

    #Convert RGB values into HSV values
    def hsv(self):
        """Convert RGB values into HSV values"""
        r, g, b = rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0
        mx = max(r, g, b)
        mn = min(r, g, b)
        df = mx - mn
        if mx == mn:
            h = 0
        elif mx == r:
            h = (60 * ((g - b) / df) + 360) % 360
        elif mx == g:
            h = (60 * ((b - r) / df) + 120) % 360
        elif mx == b:
            h = (60 * ((r - g) / df) + 240) % 360
        if mx == 0:
            s = 0
        else:
            s = df / mx
        v = mx
        return h, s, v

    def rgb_to_hls(self, r, g, b):
        """Convert rgb values to hsl values"""
        if (max(r, g, b) == 0):
            maxc = 0.002
        else:
            maxc = max(r, g, b)
        if (min(r, g, b) == 0):
            minc = 0.001
        else:
            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:
            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

    def color_difference(self, color1, color2):
        """Return a list of all the differences of colors in other lists ([diff,diff2,diff3,etc])"""
        return sum([
            abs(component1 - component2)
            for component1, component2 in zip(color1, color2)
        ])

    def dominantColor3(self):
        """Return the number value of BLUE, BLACK or WHITE > This function is used for following the path
        
        This function compare and take the nearest color
        """
        rgb = self.rgb()
        #Color references
        TARGET_COLORS = {
            "BLUE": (23, 53, 210, 117),
            "BLACK": (9, 9, 7, 9),
            "WHITE": (167, 144, 255, 199)
        }
        SWITCHER_COLOR = {
            "BLUE": Color.BLUE,
            "BLACK": Color.BLACK,
            "WHITE": Color.WHITE
        }
        rgb_list = list(rgb)
        hsl_color = self.rgb_to_hls(rgb[0], rgb[1], rgb[2])
        rgb_list.append(hsl_color[1])
        my_color = tuple(rgb_list)
        differences = [[
            self.color_difference(my_color, target_value), target_name
        ] for target_name, target_value in TARGET_COLORS.items()]
        differences.sort()
        my_color_name = differences[0][1]
        return SWITCHER_COLOR.get(my_color_name, -1)

    #Same function as dominantColor3 but white red and green
    def dominantColor4(self):
        """Same function as dominantColor3 but white red and green"""
        rgb = self.rgb()
        TARGET_COLORS = {
            "RED": (180, 40, 30, 109),
            "GREEN": (92, 154, 50, 102),
            "BLUE": (23, 53, 210, 117),
            "BLACK": (9, 9, 7, 9),
            "WHITE": (167, 144, 255, 199)
        }
        rgb_list = list(rgb)
        hsl_color = self.rgb_to_hls(rgb[0], rgb[1], rgb[2])
        rgb_list.append(hsl_color[1])
        my_color = tuple(rgb_list)
        differences = [[
            self.color_difference(my_color, target_value), target_name
        ] for target_name, target_value in TARGET_COLORS.items()]
        differences.sort()
        my_color_name = differences[0][1]
        return my_color_name

    def dominantSortingColor(self):
        """Use dominantColor4 to take a list of 5 colors and choose the most viewed color in this list"""
        my_color = self.dominantColor4()
        wait(15)
        self.dominantColorTab.append(my_color)
        if (len(self.dominantColorTab) == 5):
            setlist = set(sorted(self.dominantColorTab))
            b = [self.dominantColorTab.count(el) for el in setlist]
            pos = b.index(max(b))
            new_list = list(setlist)
            self.dominantColorTab.clear()
            return new_list[pos]
        else:
            return "N/A"

    #Same as dominantSortingColor but return the number of the color
    def dominantSortingColor2(self):
        """Same as dominantSortingColor but return the number of the color"""
        my_color = self.dominantColor4()
        self.dominantColorTab.append(my_color)
        SWITCHER_COLOR = {
            "RED": Color.RED,
            "GREEN": Color.GREEN,
            "BLUE": Color.BLUE,
            "BLACK": Color.BLACK,
            "WHITE": Color.WHITE
        }
        if (len(self.dominantColorTab) == 5):
            setlist = set(sorted(self.dominantColorTab))
            b = [self.dominantColorTab.count(el) for el in setlist]
            pos = b.index(max(b))
            new_list = list(setlist)
            self.dominantColorTab.clear()
            wait(10)
            return SWITCHER_COLOR.get(new_list[pos], -1)
        else:
            wait(10)
            return "N/A"

    #-- COLOR FINDING WITH PROBABILITIES --#

    def updateColorProbability(self):
        """Update the list of recently found colors
        
        There may be COLOR_PROBABILITY_TIME_LIMIT colors in the log list at the same time."""

        c = self.dominantColor3()

        while (self.logColors
               and (len(self.logColors) > COLOR_PROBABILITY_TIME_LIMIT)):
            self.logColors.pop(0)

        self.logColors.append(c)

    def greenColorProbability(self):
        """Return the percentage of green colors stored in the log list"""
        return float(self.logColors.count(Color.GREEN)) / float(
            len(self.logColors))

    def redColorProbability(self):
        """Return the percentage of red colors stored in the log list"""
        return float(self.logColors.count(Color.RED)) / float(
            len(self.logColors))

    def isRedOrGreen(self):
        """Find if the current color is Red, Green or none of them.

        The Green or Red color are confirmed only if the current probability is above, respectively, COLOR_GREEN_PROBA_THRESH and COLOR_RED_PROBA_THRESH"""

        c = self.dominantColor3()
        if (c == Color.GREEN
                and self.greenColorProbability() > COLOR_GREEN_PROBA_THRESH):
            return Color.GREEN
        elif (c == Color.RED
              and self.redColorProbability() > COLOR_RED_PROBA_THRESH):
            return Color.RED
        else:
            return None
Beispiel #6
0
#!/usr/bin/env pybricks-micropython

from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase

# Write your program here
colorSensor = ColorSensor()
color = colorSensor.rgb()

brick.display.clear()
brick.display.write(0, 0, ''.join(color))
Beispiel #7
0
class BroBot():
    def __init__(self):
        left_motor = Motor(Port.B)
        right_motor = Motor(Port.C)
        self.brobot = DriveBase(left_motor,
                                right_motor,
                                wheel_diameter=55,
                                axle_track=127)
        self.left_color_sensor = ColorSensor(Port.S4)
        self.right_color_sensor = ColorSensor(Port.S2)

        self.ev3 = EV3Brick()

        self.RED_ON_WHITE = 57
        self.RED_ON_BLACK = 5

        self.GREEN_ON_WHITE = 55
        self.GREEN_ON_BLACK = 4

        self.BLUE_ON_WHITE = 100
        self.BLUE_ON_BLACK = 10

        self.RED = (self.RED_ON_WHITE + self.RED_ON_BLACK) // 2
        self.GREEN = (self.GREEN_ON_WHITE + self.GREEN_ON_BLACK) // 2
        self.BLUE = (self.BLUE_ON_WHITE + self.BLUE_ON_BLACK) // 2

        self.self.start_time = time.time()
        self.execute_program = True
        self.no_line = False

    def calibrate(self):
        self.ev3.screen.print(
            "Calibrating...\nL-SENSOR: WHITE\nR-SENSOR: BLACK\nPUSH A BUTTON\nTO CONTINUE"
        )
        while True:
            if self.ev3.buttons.pressed():
                break
            continue
        rgb = self.left_color_sensor.rgb() + self.right_color_sensor.rgb()

        self.RED_ON_WHITE = rgb[0]
        self.GREEN_ON_WHITE = rgb[1]
        self.BLUE_ON_WHITE = rgb[2]

        self.RED_ON_BLACK = rgb[3]
        self.GREEN_ON_BLACK = rgb[4]
        self.BLUE_ON_BLACK = rgb[5]

        self.RED = (self.RED_ON_WHITE + self.RED_ON_BLACK) // 2
        self.GREEN = (self.GREEN_ON_WHITE + self.GREEN_ON_BLACK) // 2
        self.BLUE = (self.BLUE_ON_WHITE + self.BLUE_ON_BLACK) // 2

    def is_black(self, color_sensor):
        (red, green, blue) = color_sensor.rgb()
        if red < self.RED and green < self.GREEN and blue < self.BLUE:
            return True
        else:
            return False

    def look_for_line(self):
        turn_rate = 80
        drive_speed = 50

        right_is_black = self.is_black(self.right_color_sensor)
        left_is_black = self.is_black(self.left_color_sensor)

        if not right_is_black and not left_is_black:
            self.brobot.drive(drive_speed, turn_rate)
        if left_is_black or right_is_black:
            wait(100)
            self.execute_program = True
            self.no_line = False

    def drive_loop(self):
        self.start_time = time.time()

        while True:
            while self.no_line:
                self.look_for_line()

            while self.execute_program:
                self.run()

            if time.time() - self.start_time >= 3:
                self.start_time = time.time()
                self.execute_program = False
                self.no_line = True

    def run(self):
        turn_rate = 120
        drive_speed = 200

        right_is_black = self.is_black(self.right_color_sensor)
        left_is_black = self.is_black(self.left_color_sensor)

        if not right_is_black and not left_is_black:
            self.brobot.drive(drive_speed, 0)
        elif right_is_black and left_is_black:
            self.brobot.drive(drive_speed, 0)
        elif left_is_black:
            self.brobot.drive(50, -turn_rate)
            self.start_time = time.time()
        elif right_is_black:
            self.brobot.drive(50, turn_rate)
            self.start_time = time.time()
Beispiel #8
0
def optical_sensor_detect():
    global color_detect_loop_fast_flag
    global color_detected
    global color_detected_2
    global color_detected_name
    global color_detected_name_2
    global color_rgb_int
    global color_rgb_int_2
    global color_rgb_int_ave
    global color_rgb_int_ave_2
    global optical_sensor_run
    global optical_sensor_run_2
    global color_sound_on
    global color_sound_on_2
    global cs
    global cs_2
    global cs_error
    global cs_error_2
    error_fix_wait = 3000

    if optical_sensor_run:
        try:
            if cs_error:
                #Wait some and then try to connect again
                wait(error_fix_wait)
                cs = ColorSensor(ColorSensorPort)
                cs_error = False
            if color_detect_loop_fast_flag:
                color_rgb_int_ave = cs.reflection()
            else:
                color_rgb_int = cs.rgb()
                color_rgb_int_ave = sum(color_rgb_int) / 3
                color_detected = cs.color()
                color_detected_name = color_name(color_detected)
                if color_sound_on:
                    color_sound(color_detected, 1)
        except:
            cs_error = True
            print("Color Sensor 1 Error")
            sound_tools.play_file(SoundFile.COLOR)
            sound_tools.play_file(SoundFile.ERROR)
            sound_tools.play_file(SoundFile.ONE)

    if optical_sensor_run_2:
        try:
            if cs_error_2:
                #Wait some and then try to connect again
                wait(error_fix_wait)
                cs_2 = ColorSensor(ColorSensorPort_2)
                cs_error_2 = False
            if color_detect_loop_fast_flag:
                color_rgb_int_ave_2 = cs_2.reflection()
            else:
                color_rgb_int_2 = cs_2.rgb()
                color_rgb_int_ave_2 = sum(color_rgb_int_2) / 3
                color_detected_2 = cs_2.color()
                color_detected_name_2 = color_name(color_detected_2)
                if color_sound_on_2:
                    color_sound(color_detected_2, 2)
        except:
            cs_error_2 = True
            print("Color Sensor 2 Error")
            sound_tools.play_file(SoundFile.COLOR)
            sound_tools.play_file(SoundFile.ERROR)
            sound_tools.play_file(SoundFile.TWO)
Beispiel #9
0
#!/usr/bin/env pybricks-micropython

from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase

color_sensor = ColorSensor(Port.S1)

while True:

    color = color_sensor.color()
    ambient = color_sensor.ambient()
    reflection = color_sensor.reflection()
    rgb = color_sensor.rgb()

    print(color)
    print(ambient)
    print(reflection)
    print(rgb)

    print()

    wait(1000)
Beispiel #10
0
A = Motor(port=Port.A)
B = Motor(port=Port.B)
#Initialize the sensors.
us = UltrasonicSensor(port=Port.S1)
colorSensorV = ColorSensor(port=Port.S2)
colorSensorH = ColorSensor(port=Port.S3)
touch = TouchSensor(port=Port.S4)
#RED = 20
#GREEN = 20
#BLUE = 30
robot = DriveBase(A, B, wheel_diameter=56, axle_track=130)
arr = []
start = True
startag = False
while(start):
    (RED, GREEN, BLUE) = colorSensorV.rgb()
    (RED1, GREEN1, BLUE1 ) = colorSensorH.rgb()
    RED -=5
    GREEN -=5
    BLUE -=20
    t_1 = 0
    t_2 = 0
    print(str(RED) + " " + str(GREEN) + " " + str(BLUE))
    if(touch.pressed()):
        startag = True
    while(startag):
        if us.distance() > 100:
            (red, green, blue) = colorSensorV.rgb()
            is_black = red < RED or green < GREEN or blue < BLUE
            (red1, green1, blue1) = colorSensorH.rgb()
            is_black2 = red1 < RED1 or green1 < GREEN1 or blue1 < BLUE1
Beispiel #11
0
class robot:
    #status Variables
    position = [0, 0]
    Clawdir = -1
    lista_lobby = []
    posicao_lobby = 0
    matrix = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

    #sensors
    resetY_Sensor = None
    chromoSensor = None

    #motors
    claw_Motor = None
    y_Motor = None
    x_Motor1 = None
    x_motor2 = None
    xAxisMotors = None

    def __init__(self):
        self.resetY_Sensor = TouchSensor(Port.S2)
        self.chromoSensor = ColorSensor(Port.S1)
        self.claw_Motor = Motor(Port.A)

        self.y_Motor = Motor(Port.B)

        self.x_Motor1 = Motor(Port.C)
        self.x_Motor1.set_run_settings(200, 100)
        self.x_Motor2 = Motor(Port.D)
        self.x_Motor2.set_run_settings(200, 100)

        self.xAxisMotors = DriveBase(self.x_Motor1, self.x_Motor2, 50, 100)

        self.reset()

    def reset_Claw(self):
        self.claw_Motor.run_until_stalled(1000, Stop.BRAKE, 38)
        self.claw_Motor.run_time(5500 * -1, 1700, Stop.BRAKE)
        self.Clawdir = -1

    def reset_YAxis(self):
        self.y_Motor.run(300)
        while (self.resetY_Sensor.pressed() == False):
            wait(10)
        self.y_Motor.stop()

    def reset(self):
        self.reset_Claw()
        self.reset_YAxis()
        print("done reset")

    def toggleClaw(self):
        self.claw_Motor.run_time(5500 * self.Clawdir, 1300, Stop.BRAKE)
        self.Clawdir = -self.Clawdir

    def yAxis(self, pos):
        self.y_Motor.run_angle(100, -217.7 * pos, Stop.BRAKE, True)

    def xAxis(self, pos, dir):
        self.xAxisMotors.drive_time(dir * 18.75, 0, 1000 * pos * 4)

    def moveTo(self, xPos, yPos, resetY=True):
        dir = 1
        if (resetY):
            self.reset_YAxis()
        if (xPos - self.position[0] < 0):
            dir = -1
        self.xAxis(abs(xPos - self.position[0]), dir)
        if (not (resetY)):
            self.yAxis(yPos - self.position[1])
        else:
            self.yAxis(yPos + 0.25)
        self.position[0] = xPos
        self.position[1] = yPos

    def moveToLobby(self, pos, resetY=True):
        if (pos % 5 == 0):
            resetY = True
        self.moveTo(pos // 5 + 5, pos % 5, resetY)

    def moveToGame(self, xPos, yPos):
        if (xPos > 4 or yPos > 4):
            quit()
        self.moveTo(xPos, yPos, True)

    def readColor(self):
        while (True):
            tempList = []
            for x in range(10):
                wait(200)
                tempList += [self.testecor(self.chromoSensor.rgb())]
            tempList = list(dict.fromkeys(tempList))
            print(tempList)
            if (len(tempList) == 1):
                if (tempList[0] != 0):
                    return tempList[0]

    def readLobby(self):
        pos = 0
        self.moveToLobby(pos, True)
        while (len(self.lista_lobby) == 0
               or self.lista_lobby[-1] != 5):  #le as peças ate ler amarelo
            self.lista_lobby.append(self.readColor())
            print(self.lista_lobby[:-1])
            pos += 1
            if (self.lista_lobby[-1] != 5):
                self.moveToLobby(pos, False)
        self.lista_lobby = self.lista_lobby[:-1]
        self.reset_YAxis()
        countOfChars = {i: self.lista_lobby.count(i) for i in self.lista_lobby}
        print(countOfChars)
        global pecasExistentes
        global pecasExistentesOld
        pecasExistentes += [countOfChars[1]]
        pecasExistentes += [countOfChars[2]]
        pecasExistentes += [countOfChars[3]]
        pecasExistentes += [countOfChars[4]]
        pecasExistentesOld = pecasExistentes.copy()
        print(self.lista_lobby)

    def testecor(self, a):
        #print(a)
        if (a[0] > a[1] + a[2] and a[0] + a[1] + a[2] > 25):
            return 1  #vermelho
        elif (a[2] > a[0] + a[1] and a[0] + a[1] + a[2] > 25):
            return 2  #azul
        elif (a[0] + a[1] + a[2] < 70):
            temp = self.chromoSensor.color()
            if (temp == 3):
                return 3  #verde
            elif (temp == 1):
                return 4  #preto
            else:
                return 0  #sem cor
        elif (a[0] + a[1] + a[2] < 180):
            return 5  #amarelo

    def checkFigure(self):
        for pattern in figureSequence:
            result = match_pattern(self.matrix, globals()[pattern])
            #print(result)
            print(self.matrix)
            if (result != -1):
                for x in range(len(result[1])):
                    for y in range(len(result[1][x])):
                        if (result[1][x][y] == self.matrix[x + result[0][0]][
                                y + result[0][1]]):
                            pecasExistentes[result[1][x][y] - 1] -= 1
                            self.matrix[x + result[0][0]][y + result[0][1]] = 0
                brick.sound.file(SoundFile.DETECTED, VOLUME)
                brick.display.text(pattern)
                block = True
                while (block):
                    if Button.CENTER in brick.buttons():
                        block = False
                    wait(10)

    def movePieceTo(self, xPos, yPos):
        self.moveToLobby(self.posicao_lobby)
        self.matrix[xPos][yPos] = self.lista_lobby[self.posicao_lobby]
        self.posicao_lobby += 1
        self.toggleClaw()
        self.moveToGame(xPos, yPos)
        self.claw_Motor.run_time(1000, 1000, Stop.BRAKE)
        self.reset_YAxis()
        self.reset_Claw()
        self.checkFigure()
Beispiel #12
0
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                   SoundFile, ImageFile, Align)
from pybricks.tools import print, wait

# plug in
# S1 =  touch sensor 
# S2 =  light sensor
# S3 =  gyro sensor
# S4 =  ultrasonic sensor

touch = TouchSensor(Port.S1)
while not touch.pressed():
     wait (10)
     
light = ColorSensor(Port.S2)
light.rgb()
wait(100)
light.color()  
# returns Color.BLACK, Color.BLUE, Color.GREEN, Color.YELLOW, Color.RED, Color.WHITE, Color.BROWN or None.
wait(100)
while not (light.color() == Color.YELLOW):
     wait(100)
light.reflection()
wait(100)
light.ambient()
wait(100)

gyro = GyroSensor(Port.S3)

gyro.reset_angle(0)  # define your starting angle
while gyro.angle() < 90:
Beispiel #13
0
class robot:
    #variaveis principais
    position = [0,0]
    Clawdir = -1
    lista_lobby = []
    posicao_lobby = 0
    matrix =   [[0,0,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,0],
                [0,0,0,0,0]]

    #sensors
    resetY_Sensor = None
    chromoSensor = None


    #motors
    claw_Motor = None
    y_Motor = None
    x_Motor1 = None
    x_motor2 = None
    xAxisMotors = None

    #função de inicialização do robo
    def __init__(self):
        self.resetY_Sensor = TouchSensor(Port.S2)
        self.chromoSensor = ColorSensor(Port.S1)
        self.claw_Motor = Motor(Port.A)

        self.y_Motor = Motor(Port.B)

        self.x_Motor1 = Motor(Port.C)
        self.x_Motor1.set_run_settings(200, 100)
        self.x_Motor2 = Motor(Port.D)
        self.x_Motor2.set_run_settings(200, 100)

        self.xAxisMotors = DriveBase(self.x_Motor1,self.x_Motor2,50,100)


        self.reset()

    #metodo para resetar a garra
    def reset_Claw(self):
        self.claw_Motor.run_until_stalled(1000,Stop.BRAKE,38)
        self.claw_Motor.run_time(5500*-1, 1700,Stop.BRAKE)
        self.Clawdir = -1

    #metodo para resetar o eixo do Y
    def reset_YAxis(self):
        self.y_Motor.run(300)
        while (self.resetY_Sensor.pressed()== False):
            wait(10)
        self.y_Motor.stop()

    #metodo para combinar ambos os resets anteriores
    def reset(self):
        self.reset_Claw()
        self.reset_YAxis()
        print("done reset")

    #metodo para abrir e fechar a garra
    def toggleClaw(self):
        self.claw_Motor.run_time(5500*self.Clawdir,1300,Stop.BRAKE)
        self.Clawdir = -self.Clawdir

    #metodo para o movimento no eixo dos Y
    def yAxis(self,pos):
        self.y_Motor.run_angle(100,-217.7*pos,Stop.BRAKE,True)

    #metodo para o movimento no eixo dos X
    def xAxis(self,pos,dir):
        self.xAxisMotors.drive_time(dir*18.75, 0, 1000*pos*4)
    
    #combinação de ambos os metodos anteriores
    def moveTo(self,xPos,yPos,resetY=True):
        dir = 1
        if(resetY):
            self.reset_YAxis()
        if(xPos - self.position[0]<0):
            dir = -1
        self.xAxis(abs(xPos - self.position[0]),dir)
        if(not(resetY)): 
            self.yAxis(yPos - self.position[1])
        else:
            self.yAxis(yPos +0.25)
        self.position[0]= xPos
        self.position[1]= yPos
    
    #metodo para o movimento no lobby onde lê as peças
    def moveToLobby(self,pos,resetY = True):
        if(pos%5==0):
            resetY = True
        self.moveTo(pos//5+5,pos%5,resetY)

    #metodo para o movimento dentro do campo de jogo
    def moveToGame(self,xPos,yPos):
        if(xPos>4 or yPos>4):
            quit()
        self.moveTo(xPos,yPos,True)

    #metodo para ler a cor repitindo 10 vezes
    def readColor(self):
        while(True):
            tempList = []
            for x in range(10):
                wait(200)
                tempList += [self.testecor(self.chromoSensor.rgb())]
            tempList = list(dict.fromkeys(tempList))
            print(tempList)
            if(len(tempList)==1):
                if(tempList[0]!=0):
                    return tempList[0]

    #metodo para testar a cor individualmente
    def testecor(self,a):
        #print(a)
        if(a[0]>a[1]+a[2] and a[0]+a[1]+a[2]>25):
            return 1 #vermelho
        elif(a[2]> a[0]+a[1] and a[0]+a[1]+a[2]>25):
            return 2 #azul
        elif(a[0]+a[1]+a[2]<70):
            temp = self.chromoSensor.color()
            if(temp==3):
                return 3 #verde
            elif(temp==1):
                return 4 #preto
            else:
                return 0 #sem cor
        elif(a[0]+a[1]+a[2]<180):
            return 5 #amarelo

    #metodo que combina o movimento e a leitura de cores para ler todo o lobby
    def readLobby(self):
        pos = 0
        self.moveToLobby(pos,True)
        while(len(self.lista_lobby)==0 or self.lista_lobby[-1]!=5): #le as peças ate ler amarelo
            self.lista_lobby.append(self.readColor())
            print(self.lista_lobby[:-1])
            pos+=1
            if(self.lista_lobby[-1]!=5):
                self.moveToLobby(pos,False)
        self.lista_lobby = self.lista_lobby[:-1]
        self.reset_YAxis()
        countOfChars = {i:self.lista_lobby.count(i) for i in self.lista_lobby}
        print(countOfChars)
        global pecasExistentes
        global pecasExistentesOld
        pecasExistentes += [countOfChars[1]]
        pecasExistentes += [countOfChars[2]]
        pecasExistentes += [countOfChars[3]]
        pecasExistentes += [countOfChars[4]]
        pecasExistentesOld = pecasExistentes.copy()
        print(self.lista_lobby)

    #metodo que verifica se uma figura foi feita
    def checkFigure(self):
        #itera sobre todos os padrões e verifica se existe algum
        for pattern in figureSequence:
            result = match_pattern(self.matrix,globals()[pattern])
            print(self.matrix)
            if(result != -1):
                globals()["score"] += globals()[pattern + "p"]
                for x in range(len(result[1])):
                    for y in range(len(result[1][x])):
                        if(result[1][x][y]==self.matrix[x+result[0][0]][y+result[0][1]]):
                            pecasExistentes[result[1][x][y]-1] -= 1
                            self.matrix[x+result[0][0]][y+result[0][1]] = 0
                brick.sound.file(SoundFile.DETECTED,VOLUME)
                brick.display.text(pattern)
                block = True
                while(block):
                    if Button.CENTER in brick.buttons():
                        block = False
                    wait(10)

    #metodo que combina os metodos anteriores para mover uma peça para uma posição especifica
    def movePieceTo(self, xPos, yPos):
        self.moveToLobby(self.posicao_lobby)
        self.matrix[xPos][yPos] = self.lista_lobby[self.posicao_lobby]
        self.posicao_lobby += 1
        self.toggleClaw()
        self.moveToGame(xPos,yPos)
        self.claw_Motor.run_time(1000,1000,Stop.BRAKE)
        self.reset_YAxis()
        self.reset_Claw()
        self.checkFigure()
Beispiel #14
0
PORT = 2508  # Porta que o Servidor esta
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dest = (HOST, PORT)

ev3.speaker.say("Abrindo sensores")

corLeft = ColorSensor(Port.S2)
corRight = ColorSensor(Port.S3)

ev3.speaker.say("Analizando as cores")

#cronometro = StopWatch()
contador = 0
while (Button.CENTER not in ev3.buttons.pressed()):
    #cronometro.reset()
    left = corLeft.rgb()
    right = corRight.rgb()
    #print("Tempo sensores ", cronometro.time())

    #cronometro.reset()
    lr = "{0:.2f}".format(left[0])
    lg = "{0:.2f}".format(left[1])
    lb = "{0:.2f}".format(left[2])

    # Estas equações foram obtidas a partir dos valores ajustados
    # no script scilab
    rr = "{0:.2f}".format(right[0] + 0.048859 * right[0] + 1.236116)
    rg = "{0:.2f}".format(right[1] + 0.319633 * right[1] + 1.086458)
    rb = "{0:.2f}".format(right[2] + 0.348117 * right[2] + 4.107346)

    contador += 1
Beispiel #15
0
# Initializing the Color Sensor on the EV3
colorsensor = ColorSensor(Port.S4)

# Color Dictionary correlates the name with RGB array
colorDict = {'red': [255, 0, 0], 'green': [0, 255, 0], 'blue': [0, 0, 255]}

# Initializing the ev3 class instance
ev3 = EV3Brick()

color = ''

# The below loop waits for user input and assigns the detected color
while True:
    buttonPress = ev3.buttons.pressed()
    if len(buttonPress) > 0:
        rgb = colorsensor.rgb()
        rVal = rgb[0]
        gVal = rgb[1]
        bVal = rgb[2]
        if rVal > gVal and rVal > bVal:
            color = 'red'
        elif gVal > rVal and gVal > bVal:
            color = 'blue'
        elif bVal > rVal and bVal > gVal:
            color = 'green'
        print('Color Sensor Detected: ' + color)
        break
    print('Waiting for user input')
    wait(1000)

# Command formats the command line prompt for later call
Beispiel #16
0
#us = UltrasonicSensor(port=Port.S1)
colorSensorV = ColorSensor(port=Port.S2)
colorSensorH = ColorSensor(port=Port.S3)
touch = TouchSensor(port=Port.S4)

RED = 10
GREEN = 10
BLUE = 20

robot = DriveBase(A, B, wheel_diameter=56, axle_track=130)
start = True
startag = False
while (start):
    if (touch.pressed()):
        startag = True
    while (startag):
        print(colorSensorH.rgb())
        print(colorSensorV.rgb())
        (red, green, blue) = colorSensorV.rgb()
        is_black = red < RED or green < GREEN or blue < BLUE
        (red1, green1, blue1) = colorSensorH.rgb()
        is_black2 = red1 < RED or green1 < GREEN or blue1 < BLUE
        if not (is_black or is_black2):
            robot.drive(200, 0)
        elif (is_black):
            robot.drive(120, 90)
        elif (is_black2):
            robot.drive(120, -90)
        else:
            robot.stop()
Beispiel #17
0
# Initialize Color sensor.
colorSensor = ColorSensor(Port.S3)

# Adjust volume.
ev3.speaker.set_volume(70)

# Colors dictionary.
colors = {
    Color.BLACK: SoundFile.BLACK,
    Color.BLUE: SoundFile.BLUE,
    Color.GREEN: SoundFile.GREEN,
    Color.YELLOW: SoundFile.YELLOW,
    Color.RED: SoundFile.RED,
    Color.WHITE: SoundFile.WHITE,
    Color.BROWN: SoundFile.BROWN
}

# Test colors.
counter = 0
while counter < 5:
    wait(10)
    color = colorSensor.color()
    r, g, b = colorSensor.rgb()
    ev3.screen.print('r=', r, 'g=', g, 'b=', b, '(%)')
    ev3.screen.print('ambient', colorSensor.ambient(), '%')
    ev3.screen.print('reflection', colorSensor.reflection(), '%')
    if color != None:
        counter = counter + 1
        ev3.speaker.play_file(colors.get(color, 'unknown'))

ev3.speaker.play_file(SoundFile.GOODBYE)