1
1
1bd_1l_Bari2018-01-01 22:59:59
Programming
1bd_1l_Bari, 2018-01-01 22:59:59

How to implement: while the button is pressed - execute the command?

Good day.
Essence: the stepper motor is connected to the atmega mikruhe, which is connected to the PC via the USART interface.
An application is written on the computer in C #, where there are 4 buttons (up, down, right, left). By clicking on which, the controller receives bytes: 1, 2, 3, 4. It is necessary that while the button is pressed (for example, up), the computer sends byte 1 constantly to the controller, that is, while the button is pressed, the stepper is spinning.
Problem: in the function where the button is pressed, I wrote an eternal loop that operates while the flag == true. As soon as we release the button, the flag becomes false, and you need to exit the loop, but the loop continues, the program hangs, and the stepper spins.
How to do it right, do not tell me?
Here is the code in C# (for the controller, everything is done correctly 100%, so there is no point in posting)

void Button1MouseDown(object sender, MouseEventArgs e) //кнопка нажата
    {
      flag = true;
      while(flag)
      {
        Port_Write(1); //посылаем 1 байт на контроллер
      }
    }
    
    void Button1MouseUp(object sender, MouseEventArgs e) // кнопка отпущена
    {
      flag = false;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Silin, 2018-01-01
@1bd_1l_Bari

You enter a loop on the UI thread and recycle it tightly in the same loop. If you take a closer look, you'll notice that the button on the UI doesn't retract at all after you release it. You need to move the loop to a separate thread, like this:

void Button1MouseDown(object sender, MouseEventArgs e) //кнопка нажата
{
 Task.Run(() => {
      flag = true;
      while(flag)
      {
        Port_Write(1); //посылаем 1 байт на контроллер
      }
});
}

PS I'm not aware of the microcontroller kitchen, but maybe you shouldn't send commands with such frequency?

N
NonameProgrammer, 2018-01-02
@NonameProgrammer

And you forgot to specify an additional condition - how to exit the loop? How will the application guess that the button is no longer pressed, if there is an eternal loop ?, so it hangs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question