Simple code for stepper to move one step per input pulse with limit switches?


I did read a big portion of posts here, and did learn many things, but now I'm loosing a fill rouge, on my mature head. Can someone write a simple code for stepper rail, which I plan to use with an old winding machine, to lead a wire? The goal is- reading turns from axis with either magnetic or optical sensor, and Arduino should move nSteps per turn (depend of a thickness of wire ) and reverse direction every time that hit the limit switches. (it could be single or two button switch) Any ideas. I will be grateful for everything!

Opps.. I already have a driver for motor, so have to start with PUL and DIR. Stepper works fine, with sample code I Uploaded, while I Using a AccelStepper library.

After long time, I have try again to do something with my old winding machine. I need a wire movement, for which I have a Nema17 stepper on rail.

I decided to use manually switches for direction of stepper with HY-DIV268N driver to simplify code, and give to myself a little more time to learn. Now I use this sketch for rotary encoder, but everything I do further just make mess in sketch and my head.

// The pins the quadrature encoder is connected.
// We connect the second signal of the encoder to pin 4.
// int.1 is free for other use.
int in_a = 2;
int in_b = 4;

// The number of pulses per revolution
// depends on your index disc!!
unsigned int pulsesperturn = 36;

// The total number of revolutions
int revolutions = 0;

// Initialize the counter
volatile int pulses = 0;

void count() {
  // This function is called by the interrupt
  // If in_b is HIGH increment the counter
  // otherwise decrement it
  if (digitalRead(in_b)) {
  else {

void setup() {
  pinMode(in_a, INPUT);
  pinMode(in_b, INPUT);
  attachInterrupt(0, count, RISING);

void loop() {
  revolutions = pulses / pulsesperturn;
  // Here you can output the revolutions, e. g. once a second

// Now I would like to implement followed action
// 1.For each turn, set (n) output pulses, to use with stepper driver.
// 2.Wait for next Turn to repeat actions

I would like to get (n, 1-50) number of pulses on digital PWM pin for each turn, because the diameter of wire is (n) mm, I still hope someone can give me some hint, so I can use it in practice. later I will upgrade it to avoid mechanical switches.

Thanks for any suggest. Caspy.

It's a long time since your first post. I wonder if there is anything useful in stepper motor basics.

Can you explain a bit more about how you plan to use the encoder. What causes it to turn and what is the relationship between the encoder and the motor.

I don't understand what the "digital PWM pin" is for?