Using Push button controlling Stepper rotation with switch case

Newbie here, The goal of this is to use the switch case method, first when push button is pressed, stepper motor start spinning clockwise and button is pressed again stepper motor rotate the other way. Below the code, the push button work in controlling the rotation but its has some stuttering and I want it to be continuously



const int stepPin = CONTROLLINO_A7; //Stepper motor 
const int dirPin = CONTROLLINO_A6; //stepper direction 
const int button2 = A1; //Push button
int count= 0;
int newcount = 0;
int buttonState = 0;


void setup()
{
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(button2, INPUT);
  Serial.begin(9600);
}

void loop()
{
  if(digitalRead(button2) == HIGH) 
  {
  newcount=count + 1;
    if(newcount!=count)
    {
      switch(newcount)
      {
        case 1: 
        digitalWrite(dirPin, HIGH);
        for(int x = 0; x<1000; x++){
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(500);
         
        }
        break;
        case 2: 
        digitalWrite(dirPin, LOW);
        for(int x = 0; x<1000; x++){
          digitalWrite(stepPin, LOW);
          delayMicroseconds(500);
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(500);
        } 
         break; 
                
      } 
     count =newcount;
    }
 }
 delayMicroseconds(500);
} 

Few things
Use INPUT_PULLUP instead of INPUT
Buttons are normally wired between the DI pin (not an AI pin, but that should work) and ground. They are active when LOW, not HIGH.

if(digitalRead(button2) == HIGH)
// simplifies to:
if( !digitalRead(button2) )
//  Note the ! (not)

You want to wait on the button to be released before repeating.

why not have a direction variable that is toggled whenever the button is pressed dir = ! dir;. a common routine can then be used to drive the motor

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