|
| 1 | +from pybricks.tools import wait |
| 2 | +from pybricks.parameters import ImageFile, Button, Port, Color |
| 3 | +from pybricks.hubs import EV3Brick |
| 4 | +from pybricks.ev3devices import Motor |
| 5 | + |
| 6 | +from _ev3_motor_dc import motor_set_dc |
| 7 | + |
| 8 | + |
| 9 | +# True means A&D pair is active. False means B&C pair is active. |
| 10 | +pair_ad_active = False |
| 11 | + |
| 12 | +# Power used for all motors if active. |
| 13 | +POWER = 100 |
| 14 | + |
| 15 | +# Preload to avoid repeated allocation. |
| 16 | +IMG_POS = ImageFile._ROTATE_CW18 |
| 17 | +IMG_NEG = ImageFile._ROTATE_CCW18 |
| 18 | +IMG_AD = ImageFile._APP_MOTOR_CONTROL_AD |
| 19 | +IMG_BC = ImageFile._APP_MOTOR_CONTROL_BC |
| 20 | + |
| 21 | +# UI is one of two prebuilt images from lms2012. |
| 22 | +ev3 = EV3Brick() |
| 23 | + |
| 24 | + |
| 25 | +def draw_ui(): |
| 26 | + file = IMG_AD if pair_ad_active else IMG_BC |
| 27 | + ev3.screen.draw_image(0, 20, file) |
| 28 | + ev3.screen.draw_box(0, 0, 177, 16, fill=True, color=Color.WHITE) |
| 29 | + |
| 30 | + |
| 31 | +draw_ui() |
| 32 | + |
| 33 | +while True: |
| 34 | + # Start with light on and motors off. |
| 35 | + draw_ui() |
| 36 | + ev3.light.on(Color.GREEN) |
| 37 | + for m in range(4): |
| 38 | + motor_set_dc(m, 0) |
| 39 | + |
| 40 | + # Wait for anything to happen. |
| 41 | + while not (pressed := ev3.buttons.pressed()): |
| 42 | + wait(10) |
| 43 | + |
| 44 | + # Center button toggles motor pair |
| 45 | + if Button.CENTER in pressed: |
| 46 | + pair_ad_active = not pair_ad_active |
| 47 | + draw_ui() |
| 48 | + while any(ev3.buttons.pressed()): |
| 49 | + wait(10) |
| 50 | + continue |
| 51 | + |
| 52 | + # Determine motor power for horizontal buttons. |
| 53 | + dc_x = 0 |
| 54 | + if Button.RIGHT in pressed: |
| 55 | + dc_x += POWER |
| 56 | + if Button.LEFT in pressed: |
| 57 | + dc_x -= POWER |
| 58 | + |
| 59 | + # Determine motor power for vertical buttons. |
| 60 | + dc_y = 0 |
| 61 | + if Button.UP in pressed: |
| 62 | + dc_y += POWER |
| 63 | + if Button.DOWN in pressed: |
| 64 | + dc_y -= POWER |
| 65 | + |
| 66 | + # Activity heartbeat. |
| 67 | + if dc_x or dc_y: |
| 68 | + ev3.light.blink(Color.GREEN, [100, 100, 800, 100]) |
| 69 | + else: |
| 70 | + ev3.light.on(Color.GREEN) |
| 71 | + |
| 72 | + # Drive one or two motors. |
| 73 | + output = [0, 0, 0, 0] |
| 74 | + index_x = 3 if pair_ad_active else 2 |
| 75 | + index_y = 0 if pair_ad_active else 1 |
| 76 | + output[index_x] = motor_set_dc(index_x, dc_x) |
| 77 | + output[index_y] = motor_set_dc(index_y, dc_y) |
| 78 | + |
| 79 | + # Draw output indicators if active. |
| 80 | + for m in range(len(output)): |
| 81 | + if output[m]: |
| 82 | + ev3.screen.draw_image(20 + m * 40, 2, IMG_POS if output[m] > 0 else IMG_NEG) |
| 83 | + |
| 84 | + # Keep going until button state changes. |
| 85 | + while ev3.buttons.pressed() == pressed: |
| 86 | + wait(10) |
0 commit comments