Programming bipolar motor to specific number of steps

Good day, I am currently working on a project where I need to program a bipolar motor to turn according to a specific step count or angle when a microswitch state is switched to HIGH. So far I have been able to get the motor to activate upon the switch being activated, but only for as long as the switch is engaged and not according to a specific step count.

I am using an Arduino Mega 2560 with a Nema 23 and TB6600 driver. I have wired the microswitch in the standard buttonState configuration and when the buttonState is HIGH it outputs the signal for the motor to start.

Here is the code, but I am not sure how to define that the motor should take a specific number of steps and continue until the required number have been taken and not only step for as long as the switch is engaged. The buttonState will only be high for a second or less, but the motor must keep turning until the specified number of steps have been taken.

#include <Stepper.h>
int buttonState = 0;
const int Button = 7;
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution,8,9);
int stepCount = 0;

void setup() {
pinMode(Button, INPUT);

void loop() {
buttonState = digitalRead(Button);
if (buttonState==HIGH)

Hope I have been clear enough on what is currently happening vs. what I need it to do. Thanks for any and all help.


Please follow the advice given in the link below when posting code. Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

Look at what the functions in Stepper.h provides. Is there a function that makes a certain number of steps?
Does stepper need being kicked until the move is finished?
Do some more research and see what You can find out.

Was able to get it working the way I require. I am sure that the Stepper.h library can be used to get the movement I require, but was able to get it done much easier using AccelStepper.h.

You certainly don't want to use Stepper.h with a NEMA23 stepper, speed-ramping is essential for large steppers for any kind of performance due to the large inertia of the rotor. Unless you have a micro-miniature stepper or only want a few rpm, AccelStepper (in particular its speed-ramping) are what's needed.

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