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:
myStepper.setSpeed(60);
// initialize the serial port:
Serial.begin(9600);
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){
myStepper.step(-stepsPerRevolution);
delay(1000);}
// step one revolution in the other direction:
{
while (digitalRead(2) == LOW){
myStepper.step(stepsPerRevolution);
delay(1000);
}}}}