Pregunta

i'm currently developping a program that runs on a robot. The program needs to add positions to a list but you have to push a button to add a new position. This has to be inside a while loop. But when i press the button the function repeats itself multiple times instead of just 1. Here is the part of code:

while not self.done():
    if self._io_left_lower.state:
        self._gripper_left.open()
    elif self._io_left_upper.state:
        self._gripper_left.close()
    if self._io_right_lower.state:
        self._gripper_right.open()
    elif self._io_right_upper.state:
        self._gripper_right.close()
    if self._io_left_nav.button0:
        print("repeats")
        #self._mapping.append([self._limb_left.joint_angles(), self._gripper_left.position()])
    if self._io_right_nav.button0:
        self._mapping.append([self._limb_right.joint_angles(), self._gripper_right.position()])
    if self._io_left_nav.button1:
        self.stop()

As you can see when the self._io_left_nav.button0 is pressed it will now just print 'repeats' several times but it has to to be printed just onces. same for the self._io_right_nav.button0.

¿Fue útil?

Solución

If button0 is a physical button and your loop is polling the button state then it is normal that many iterations run in the time your button is being pressed. You have several options to solve this situation, two of them are:

  • Do not use a loop check the button but hardware interruptions used to keep an updated representation of your state.
  • If you still want to use your loop, you should detect button state changes instead checking its current state at each iteration. That may require your program to implement a noise filter.

A very simple way to implement the second option is to have a button state variable with a timestamp associated: At each loop iteration, if the difference between the current time and the timestamp is big enought then you should check if the current state is the same than the one stored in the variable. If not then you have detected a change. In any case, at this point you should update your state-timestamp variable.

This is an example:

from time import time
prevState = (False,time())
while not self.done():
    current = time()
    if self._io_left_nav.button0 and (current-prevState[1])*1000>2: #For example, 2 ms
        if self._io_left_nav.button0 != prevState[0]:
            print("repeats")
        prevState = (self._io_left_nav.button0,time())

Otros consejos

I presume that's some kind of flag, that the button was pressed.

If you don't clear the state, the condition in the if statement will evaluate true. Again, and again....

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top