How do I get my code to loop until I press a button (Lego EV3)

819 views Asked by At

The question pure and simple. I've tried using while loops, rearranging code, but all that happens is that the program starts when i press the button or does absolutely nothing at all. Can anyone see what I am doing wrong?

#!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_B, OUTPUT_C
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from time import sleep
import time

sound = Sound()
btn = Button()
tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)

def movement(left_speed, right_speed, rotations):
tank_pair.on_for_rotations(left_speed, right_speed, rotations, brake=True, block=True)


while not btn.any():
movement(20,20,10)
movement(-100,0,1.5)
movement(20,20,10)
sleep(0.01)

while btn.any():
sleep(0.01)
tank_pair.off()
sound.beep()
exit()
2

There are 2 answers

1
Jasar Orion On

you can break your main loop using this

pip install keyboard

then

import keyboard

while True:
    # do something
    if keyboard.is_pressed("q"):
        print("q pressed, ending loop")
        break
6
krmogi On

Your indentation is incorrect.

from ev3dev2.motor import MoveTank, OUTPUT_B, OUTPUT_C
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from time import sleep
import time

sound = Sound()
btn = Button()
tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)

def movement(left_speed, right_speed, rotations):
    tank_pair.on_for_rotations(left_speed, right_speed, rotations,       brake=True, block=True)


while not btn.any():
    movement(20,20,10)
    movement(-100,0,1.5)
    movement(20,20,10)
    sleep(0.01)

while btn.any():
    sleep(0.01)
    tank_pair.off()
    sound.beep()
    exit()