What's wrong? Push button in middle of loop works half the time

Can anyone find what’s wrong with this sketch?

We are using a Nano with a L9110 driver to a stepper motor back and forth. The objective is to interrupt a loop two times with a push button: the first click on the button moves the stepper +200, the next push on the button moves it -200.

But the code is causing problems, and it often moves +200 two or three times in a row. Or the opposite. Obviously this is not a stable code. Can someone help with this?

Here is the code:

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  // initialize the serial port:
  pinMode(2, INPUT_PULLUP);//this activates the pullup resistor to make the button work

void loop() {
  // step one revolution  in one direction:
    while (digitalRead(2) == LOW){

  // step one revolution in the other direction:
    while (digitalRead(2) == LOW){

You’re going to miss button presses during those big, long delays.

This is NOT and installation and troubleshooting issue.

Sorry for posting in the wrong place.

Where does this post belong?

This post has been on the board for close to a month and no-one has answered it. Judging from the amount of discussion in the other posts on the board, one would think there was a problem with this post that is preventing it from getting answered..

Is there a better way for the question to have been asked?

Awol did answer it. Those delays are the problem.

Is there a better way for the question to have been asked?

Well, you could have included a circuit description and / or schematic.

You could have explained what

The objective is to interrupt a loop


You could have used the IDE’s auto-format tool, so that


doesn’t happen.

You would be better off reading the button once and have another variable that determines which way you should go this time. After the move, flip the variable to the other direction.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.