Problems with breaking out of "for" loop using a PushButton

So all in all you want to have a toggle-switch which does:

first press of the button: start rotating the servo continuosly

second press of the button: stop servo-rotation

third press of the button: start rotating the servo continuosly

forth press of the button: stop servo-rotation

This means your code needs a logic to transform a short button-press into a continously hold "state" "run servo" which alternaties with the state "servo is idle"

The code shall be responsive all the time regardless of where the servo is at rotating

This means you need non-blocking timing.

The servo-rotation-speed shall be slowed down which requires some waiting-time after each small step of servo-rotation.

There is another servo-library that is able to move servos slowly automatically "in the backround". This is the MobaTools-library which can be installed with the Arduino-IDE library-manager.

You set a servo-speed and when-ever you command a new servo-position the servo-rotates slowly towards the new position. You don't have to care about the details

a simple

Myservo.write (180);
// check if servo has reached position 180 then
MyServo.write(0);

will be enough. The library itself will take care about the slow movement.

For the functionality toggle a state with a single momentary push-button
I have written a demo-code not long ago

If you like take a look at it.
Regardless of you beeing a real newcomer or already have some coding-knowledge I'm very interested in the question you have about this demo-code.
Whatever the questions will be post your questions.

I'm very interested in making this demo-code as easy to understand as possible.

Be the change you want to see in the world
best regards Stefan

1 Like