Some Help with Stepper motor

Hello Guys!

i am having a problem with the motor code and wanted some help!!!

I am using an Button to simulate the Sensor.

I wanted to put an sensor infrared photo Interruptor (Old Scanners) with an stepper motor to an arduino.

I am using L297 + L298N Module.

My Code:

#define ccw 5
#define clock 4
#define button 6
void setup()
{
  Serial.begin(9600);
   pinMode(ccw,OUTPUT);
   pinMode(clock,OUTPUT);
   pinMode(button, INPUT);
}
int motorone (){
int i;
for(i = 0; i<30; i++)
	 {
	    digitalWrite(ccw, HIGH);
	    digitalWrite(clock, HIGH);
	    delay(100);
	    digitalWrite(clock, LOW);
	    delay(100);
	 }
}
int motortwo(){
int j;
for(j=0;j<30; j++)
	 {
	    digitalWrite(ccw, LOW);
	    digitalWrite(clock, LOW);
	    delay(100);
	    digitalWrite(clock, HIGH);
	    delay(100);
	 }
}
void loop()
{   int buttonState = digitalRead(button);
   if(buttonState==0){
   digitalWrite(clock, LOW);
   }
   
   if(buttonState == 1)
   {
   Serial.println(buttonState);
   motorone();
   }
   if(buttonState == 1)
   {
     motortwo();
   }
 }

When i put the Button to 0, it waits the loop terminate to stop the motor. I wanted to terminate it immediatly.



Any Help how could i do it?
Thanks for helping.

There are two problems with your program.

Don't use delay() as nothing can happen during a delay interval. Use millis() to manage timing without blocking if you want a responsive program. See Several Things at a Time

Your code goes through a complete move using FOR before it checks the switch. If you want it to be responsive it should do

checkSwitch
step
repeat

You can change your code so as not to use FOR and instead just use a variable to keep track of how many steps have happened. That way each iteration of loop() will cause a step until the limit is reached.

...R
Stepper Motor Basics

Hi,

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

How have you got your button wired, have you a pull up or down resistor wired in to the input pin of the controller?
I don,t see the internal pull-up activated in the sketch?

Tom… :slight_smile: