Stepper motor with Pot

hello guys I want to move a stepper motor with a potentiometer and im doing without libreries.

potentiometer starts in 0 always.

with the map() function I simulate 20 steps for my motor to get 360 degrees.

as you can see I use 4 leds simulating my step motor coils (remember this is just simulating, when I get my real step motor i will change map() for steps and i will change digitalWrite for leds), for 1 step forward my simulation is led1, led2, led3, led4 blinks and off simultaneously, and for 1 step after my simulation is led4, led3, led2, led1, simultaneously.

everything is working fine it has a counter called “n” which will be my feedback (i want to call it like this).

for example

if i move potentiometer to 10 then after the program starts i move fast to 5. it will start step forward simulation led1, led2, led3, led4, untill my feedback “n” reaches 10 times it will stop and will start to do simulation for after led4, led3, led2, led1 untill it reaches 5.

i want this to be in real time like if i move potentiometer to 10 it starts the program, and when feedback “n” is like 7 then I move potentiometer to 5, it will inmediately stop simulation for forward and will start simulation for after starting from 7 to 5 instead of reaching 10 then going to 5.

I will write the program here because i cant attach it. please understand im a beginner.

/*
	   En este proyecto leemos el valor de un potenciometro
	   y con este valor damos velocidad a un motor paso a paso

	 */

	   // Declaramos las constantes que vamos a usar
	   const int pinSensor1 = 0;   // pin del sensor analogico, con un potenciometro
	   // Declaramos las variables que vamos a usar
	   int velocidad1          = 0; //variable para guardar valor del potenciometro
       int velocidad2          = 0;// variable para guardar el valor 
       int velocidad3          = 0;
	   int valorPotenciometro1 = 0;
       int led1          = 2;
       int led2          = 4;
       int led3          = 7;
       int led4          = 8;
       int led5          = 12;
       int led6          = 13;
       int led7          = 11;
       float n          = 0; //variable para guardar el valor de "n" siendo n un contador
	   void setup() {
	       pinMode(pinSensor1, INPUT); // Incializa el pin del pot como entrada
           pinMode(led1, OUTPUT);
           pinMode(led2, OUTPUT);
           pinMode(led3, OUTPUT);
           pinMode(led4, OUTPUT);
           pinMode(led5, OUTPUT);
           pinMode(led6, OUTPUT);
           pinMode(led7, OUTPUT);
	   }
	   void loop(){
	       valorPotenciometro1 = analogRead(pinSensor1);     //  Lee el valor del sensor
           velocidad1 = map(valorPotenciometro1, 0, 1023, 0, 20);//  Transforma  este valor en el valor que usaremos con funcion map
           velocidad2= map(velocidad1, 0 ,100,100,0);//futuros valores
           velocidad3= map(velocidad1, 140 ,255,0,255);//futuros valores
         
         if ((velocidad1)<20)// una vuelta completa del pot es igual a 20 segun el mapeo aqui solo mide que sea verdad
{    
           if ((velocidad1)>n)// comprueba que el valor del pot sea mayor a "n" nuestro contador 
           {
             if (velocidad1>0) // comprueba que giremos primero el pot para empezar secuencia
             {
           for (int i=0;n<velocidad1;i++) //empezara secuencia de bucle cuando giremos el pot
           {
             digitalWrite(led1, HIGH);
             delay(100);
             digitalWrite(led1, LOW);
             delay(100);
             digitalWrite(led2, HIGH);
             delay(100);
             digitalWrite(led2, LOW);
             delay(100);
             digitalWrite(led3, HIGH);
             delay(100);
             digitalWrite(led3, LOW);
             delay(100);
             digitalWrite(led4, HIGH);
             delay(100);
             digitalWrite(led4, LOW);
             delay(100);
             digitalWrite(led5, HIGH);
             n=n+1;                    // aqui iremos sumando nuestro contador para llegar a ser igual a velocidad1   
           }               
           }            
           }   
}
           if ((velocidad1)<n) // aqui mide que cuando velocidad1 sea mayor a nuestro contador ejecute
           {
           for (int j=0;n>velocidad1;j++) // empezara la secuencia de bucle cuando velocidad 1 sea menor a n
           {
             digitalWrite(led4, HIGH);
             delay(100);
             digitalWrite(led4, LOW);
             delay(100);
             digitalWrite(led3, HIGH);
             delay(100);
             digitalWrite(led3, LOW);
             delay(100);
             digitalWrite(led2, HIGH);
             delay(100);
             digitalWrite(led2, LOW);
             delay(100);
             digitalWrite(led1, HIGH);
             delay(100);
             digitalWrite(led1, LOW);
             delay(100);
             digitalWrite(led6, HIGH);
             n=n-1;                       // disminuira nuestro contador
}           
         }

You could have posted your code correctly.

What is led1 supposed to be? Is that a pin number? Or, is that the state of a pin? Meaningful names will make your code self-documenting. Your code requires a lot of guessing.

If you want responsive code, you do NOT use delay.

and im doing without libreries.

Why? There is NO reason to re-invent the wheel.

PaulS: You could have posted your code correctly.

sir im sorry i just couldnt, i really tried.

PaulS: What is led1 supposed to be? Is that a pin number? Or, is that the state of a pin? Meaningful names will make your code self-documenting. Your code requires a lot of guessing.

led1,led2,led3,led4 are simulating coils of a stepper mottor.

PaulS: If you want responsive code, you do NOT use delay. Why? There is NO reason to re-invent the wheel.

delay is only for the stepper motor and the reason is because my teacher wanted like this..

thank you

led1,led2,led3,led4 are simulating coils of a stepper mottor.

I like chocolate ice cream.

Does my reply make any sense? Yours doesn't, either.

The variables hold data. That data might be a pin number. That data might be a pin state. One should be able to look at a variable name and make reasonable assumptions about the value that the variable holds. One would not expect ledPin1 to contain the state of a pin. One would not expect ledState1 to hold a pin number. But, led1 could hold anything, and we have no clue how to interpret the value.

If the value in led1 is supposed to be a stepper motor coil pin number, then led1 is a REALLY stupid name for the variable. The fact that you are testing the code using LEDs makes no difference. It is silly to have to rewrite the code when you actually have a stepper motor.

You really don't plan to connect the stepper motor directly to the Arduino, do you?

PaulS: I like chocolate ice cream.

Does my reply make any sense? Yours doesn't, either.

The variables hold data. That data might be a pin number. That data might be a pin state. One should be able to look at a variable name and make reasonable assumptions about the value that the variable holds. One would not expect ledPin1 to contain the state of a pin. One would not expect ledState1 to hold a pin number. But, led1 could hold anything, and we have no clue how to interpret the value.

If the value in led1 is supposed to be a stepper motor coil pin number, then led1 is a REALLY stupid name for the variable. The fact that you are testing the code using LEDs makes no difference. It is silly to have to rewrite the code when you actually have a stepper motor.

You really don't plan to connect the stepper motor directly to the Arduino, do you?

Ok lets start

first of all you know a stepper motor have 2 coils, so you need 4 pins, 2 for each coil.

names led1,led2,led3,led4 are the names for those pins, and who cares how i call it? if is stupid for you it really do not make any trouble for me.

on the program i am simulating that for one step clockwise i will need to give 5 volts to led1,led2,led3,led4, simultaneously, thats why i use for, and inside for is the digitalWrite( led#, HIGH).

no i dont plan to connect directly thats why i use PINS led1,led2,led3,led4 because with this i connect to transistor and after transistor i connect step motor.

do you have any idea how to help me with my code?.

on the program i am simulating that for one step clockwise i will need to give 5 volts to led1,led2,led3,led4, simultaneously

That is NOT how to make a stepper motor step.

do you have any idea how to help me with my code?.

No. You have not said what the code actually does. You have not said what you expect it to do. You have not used names that make any sense.

Other people might. I'm done.

do you have any idea how to help me with my code?.

Why don’t you start by telling us where you got this code. Did you just make it up ?
(because you sure didn’t get it off the web or from a textbook)

for (int i=0;n<velocidad1;i++) //empezara secuencia de bucle cuando giremos el pot
           {
             digitalWrite(led1, HIGH);
             delay(100);
             digitalWrite(led1, LOW);
             delay(100);
             digitalWrite(led2, HIGH);
             delay(100);
             digitalWrite(led2, LOW);
             delay(100);
             digitalWrite(led3, HIGH);
             delay(100);
             digitalWrite(led3, LOW);
             delay(100);
             digitalWrite(led4, HIGH);
             delay(100);
             digitalWrite(led4, LOW);
             delay(100);
             digitalWrite(led5, HIGH);
             n=n+1;                    // aqui iremos sumando nuestro contador para llegar a ser igual a velocidad1   
           }               
           }            
           }   
}
           if ((velocidad1)<n) // aqui mide que cuando velocidad1 sea mayor a nuestro contador ejecute
           {
           for (int j=0;n>velocidad1;j++) // empezara la secuencia de bucle cuando velocidad 1 sea menor a n
           {
             digitalWrite(led4, HIGH);
             delay(100);
             digitalWrite(led4, LOW);
             delay(100);
             digitalWrite(led3, HIGH);
             delay(100);
             digitalWrite(led3, LOW);
             delay(100);
             digitalWrite(led2, HIGH);
             delay(100);
             digitalWrite(led2, LOW);
             delay(100);
             digitalWrite(led1, HIGH);
             delay(100);
             digitalWrite(led1, LOW);
             delay(100);
             digitalWrite(led6, HIGH);
             n=n-1;                       // disminuira nuestro contador
}

The above is not a stepper motor sequence.

Did you look in your textbook for the step sequence (the above certainly did not come from any textbook)

You need to prove that you actually KNOW what the proper step motor sequence is.
Post the following:

1-Stepper Motor Sequence for FULL STEP
2- Stepper Motor Sequence for HALF STEP
3- Stepper Motor Sequence for 1/4 STEP STEP
4- Stepper Motor Sequence for 1/8 STEP

If you like you can use binary to represent the sequence:
ie:
step sequence ABCD
1: 1001
2: 1100
3: 0110
4: 0011

etc.

Do you , or do you not actually KNOW what the proper step sequence is for a bipolar stepper motor ?
Is there any point in discussing your posted code if you don’t ?
Where EXACTLY did you get the information which led you to use the sequence you posted ?
Why am I asking these questions ?
The problem is your misinformation as reflected by your code. We need to get to the bottom of that and then we can proceed with the correct approach. This is obviously a school project so why don’t you tell us what led you to post the code that you used ? (was it your idea or a fellow student ?)
Did you try Googling Bipolar Stepper Motor Step Sequence

This is not a question about bipolar steppers, this is about sequencing any abstract stepper motor from a
position signal - ie a feedback loop essentially. The stepper is emulated with LEDs, that’s not the problem.

And bipolar steppers were certainly not mentioned.

My take on this is that the OP wants a mechanism to respond immediately to the desired position
(in real-time) given by the reading from the input potentiometer. Something like

int current_position = 0;
int target_position = 0;

void handle_pot ()
{
  target_position = analogRead(pinSensor1);
}

void handle_output ()
{
  if (current_position < target_position)
    step (true) ;
  else if (current_position > target_position)
    step (false) ;
}

void step (boolean direction) 
{
  if (direction)
    current_position ++ ;
  else
    current_position -- ;
  update_leds () ;// here step to the next pattern in the sequence - code to be written
  delay (10) ; // or whatever is sensible
}

void loop ()
{ 
  handle_output () ;
  handle_pot () ;
}

The key point is to only step one step at a time. To show this in a sequence of LEDs means writing
a little state-machine driven from the step() function above. It could be quite simple like:

void update_leds ()
{
  byte phase = current_position & 3 ;
  digitalWrite (led1, phase == 0) ;
  digitalWrite (led2, phase == 1) ;
  digitalWrite (led3, phase == 2) ;
  digitalWrite (led4, phase == 3) ;
}

AlejandraG: who cares how i call it? if is stupid for you it really do not make any trouble for me.

I don't care what names you use in code that you are using for yourself.

But when you want someone to give you help for free isn't it sensiblle to make it as easy as possible for them to understand your code by using meaningful variable names.

It is also not a great idea to imply that your potential helpers are stupid. (You need to read "How to win friends and influence people")

...R

I wrote that book...

raschemmel: I wrote that book...

You are looking very good for your age.

...R

You are looking very good for your age.

Of course I would agree with you but the joke was actually intended with a different meaning that you shouldn’t have any problem getting… ;D

his is not a question about bipolar steppers, this is about sequencing any abstract stepper motor from a
position signal - ie a feedback loop essentially. The stepper is emulated with LEDs, that’s not the problem.

And bipolar steppers were certainly not mentioned.

My take on this is that the OP wants a mechanism to respond immediately to the desired position
(in real-time) given by the reading from the input potentiometer

While your idea may be valid and something the OP should consider, based on the OP’s own words,
it is clearly not what he said or meant.

Ok lets start

first of all you know a stepper motor have 2 coils, so you need 4 pins, 2 for each coil.

names led1,led2,led3,led4 are the names for those pins, and who cares how i call it? if is stupid for you it really do not make any trouble for me.

on the program i am simulating that for one step clockwise i will need to give 5 volts to led1,led2,led3,led4, simultaneously, thats why i use for, and inside for is the digitalWrite( led#, HIGH).

no i dont plan to connect directly thats why i use PINS led1,led2,led3,led4 because with this i connect to transistor and after transistor i connect step motor.

He uses the word “simulating” and specifically states that the led1, led2 etc. signals would drive transistors that would drive the coils.
This statement:

on the program i am simulating that for one step clockwise i will need to give 5 volts to led1,led2,led3,led4, simultaneously, thats why i use for, and inside for is the digitalWrite( led#, HIGH).

contradicts this statement:

no i dont plan to connect directly thats why i use PINS led1,led2,led3,led4 because with this i connect to transistor and after transistor i connect step motor.

an unbiased observer might remark “he meant both , at the same time, Mark’s idea, and raschemmel’s interpretation” which makes even less sense .

No , I think you cannot argue that once the OP claimed that the led1, led2 etc signals would drive the coil driver transistors , then it there is no ambiquity about what he meant, and when you look at his code , there is no doubt that no stepper would turn with that code.
So yeah, a visual step display is a good idea, but clearly the OP is confused about the code. He needs to repost and define TWO code blocks,
1-Led step display code
2- Motor coil simulation code
since the REAL coil DRIVER code does not accomplish the OP’s objective of displaying the steps .

I think there is problem with his MAP code as well:

 valorPotenciometro1 = analogRead(pinSensor1);     //  Lee el valor del sensor
           velocidad1 = map(valorPotenciometro1, 0, 1023, 0, 20);//  Transforma  este valor en el valor que usaremos con funcion map
           velocidad2= map(velocidad1, 0 ,100,100,0);//futuros valores
           velocidad3= map(velocidad1, 140 ,255,0,255);//futuros valores
         
         if ((velocidad1)<20)// una vuelta completa del pot es igual a 20 segun el mapeo aqui solo mide que sea verdad
{    
           if ((velocidad1)>n)// comprueba que el valor del pot sea mayor a "n" nuestro contador 
           {
             if (velocidad1>0) // comprueba que giremos primero el pot para empezar secuencia

Good luck following this : (I have no idea what he is saying)

with the map() function I simulate 20 steps for my motor to get 360 degrees.

as you can see I use 4 leds simulating my step motor coils (remember this is just simulating, when I get my real step motor i will change map() for steps and i will change digitalWrite for leds), for 1 step forward my simulation is led1, led2, led3, led4 blinks and off simultaneously, and for 1 step after my simulation is led4, led3, led2, led1, simultaneously.

everything is working fine it has a counter called “n” which will be my feedback (i want to call it like this).

for example

if i move potentiometer to 10 then after the program starts i move fast to 5. it will start step forward simulation led1, led2, led3, led4, untill my feedback “n” reaches 10 times it will stop and will start to do simulation for after led4, led3, led2, led1 untill it reaches 5.

i want this to be in real time like if i move potentiometer to 10 it starts the program, and when feedback “n” is like 7 then I move potentiometer to 5, it will inmediately stop simulation for forward and will start simulation for after starting from 7 to 5 instead of reaching 10 then going to 5.

???

The OP uses the word "simulating " but then says this:

remember this is just simulating, when I get my real step motor i will change map() for steps and i will change digitalWrite for leds)

Either it’s a simulation and it would actually drive a stepper or it is NOT a simulation and is a LED step display. If he has leds then you can’t say you are simulating leds (when you already have leds) so if you are simulating something , what are you simulating because it is clearly not stepper motor coils.

Stepper Motor Knob

with the map() function I simulate 20 steps for my motor to get 360 degrees.

Ok, let’s think about this for a second. It’s a stepper motor. It has a steps/revolution spec. Mine are 200 steps per revolution (which happens to be 360 degrees0. Now do you think I can get my stepper motor to do 1 revolution by running the OP’s MAP function ?

on the program i am simulating that for one step clockwise i will need to give 5 volts to led1,led2,led3,led4, simultaneously, thats why i use for, and inside for is the digitalWrite( led#, HIGH).

Can somebody please explain what this means:

i want this to be in real time like if i move potentiometer to 10 it starts the program, and when feedback “n” is like 7 then I move potentiometer to 5, it will inmediately stop simulation for forward and will start simulation for after starting from 7 to 5 instead of reaching 10 then going to 5.

as you can see I use 4 leds simulating my step motor coils (remember this is just simulating, when I get my real step motor i will change map() for steps and i will change digitalWrite for leds), for 1 step forward my simulation is led1, led2, led3, led4 blinks and off simultaneously, and for 1 step after my simulation is led4, led3, led2, led1, simultaneously.

If the four leds are simulating the stepper motor (NOT STEP MOTOR) coils, then they are NOT going to do this:

for 1 step forward my simulation is led1, led2, led3, led4 blinks and off simultaneously, and for 1 step after my simulation is led4, led3, led2, led1, simultaneously.

They are going to do this:

step sequence ABCD
1: 1001
2: 1100
3: 0110
4: 0011

raschemmel: Of course I would agree with you but the joke was actually intended with a different meaning that you shouldn't have any problem getting... ;D

I hope I am not that unkind :) :)

...R

I just discovered something interesting. I tried to quote Robbie’s post to correct an error he made but it didn’t show up in the quoted text. He edited it between my viewing it and hitting the “quote” button and the forum only gave me the new text.

Interesting.

I usually don't leave text that was wrong when I am correcting it because it just confuses people. I reread my posts and when I spot something I said in error (like the Motor Knob won't work with unipolar motors because they can't reverse direction (what was I thinking) ) I just delete the erroneous information or replace it with correct information. In this case it was such a dumb mistake I chose to just delete it. (sorry for any inconvenience that might have caused)

I am still confused about what the OP's objective is. I can't understand his post but I am familiar with the stepper motor Knob sketch where the stepper shaft tracks the motor knob. I don't know if that's what he wants.

Yeah, I did roll-your-own stepper code too because I wanted it to run asynchronously. I wanted an emergency stop button, but you would also need to do this to control two motors independently.

My stepper was a unipolar stepper. I kept an int for position, and watched millis() so as to not update the stepper more than once per 4ms. The key is that to get the coil sequence
A B
A ~B
~A ~B
~A B

the trick is to look at just the lowest two bits n1 and n0 of your counter n. A is equal to n1, and B is equal to (n1==n0).

Ah - here we are: blog post is here. You are interested in the MyStepper class.

call moveUp, moveDown, stopMoving. Or, if you make a note of a location and move it around a bit, you can return it to wherever it was by calling moveTo. My blind controller works by you adjust the position, hit the “set” button, and at dawn it moves the blind to the set position.

// A stepper motor that keeps track of location. It can move the motor to a target, or just start and stop.
// it will only do 5 minutes max of movement before stopping unconditionally
// call loop() to make it go.

class MyStepper {
  public:

    int location = 0;
    char *name = "Stepper";

    void setup() {
      STEPPER_PINS(v) pinMode(v, OUTPUT);
    }

    boolean loop() {
      // it's ok to leave lastMove uninitialized, because it's unsigned

      // 4ms = 250/s = 10/s turns = 600rpm, which is about the maximum

      if (millis() - lastMove < 5) return movingUp || movingDown || moveToTarget;

      lastMove = millis();

      if (movingUp) {
        location++;
      }
      else if (movingDown) {
        location--;
      }
      else if (moveToTarget) {
        if (location == target) {
          stopMoving();
          return true;
        }

        location += target > location ? 1 : -1;
      }
      else {
        return false;
      }

      if (tripFailsafe()) return true;

      // this code may cause both A and A_ to be turned on at the same time, but meh -
      // it's only for a microsecond or so. It isn't going to break anything.
      digitalWrite(A,   (location & 2) ? HIGH : LOW);
      digitalWrite(A_, !(location & 2) ? HIGH : LOW);
      digitalWrite(B,   ((location ^ (location >> 1)) & 1) ? HIGH : LOW);
      digitalWrite(B_, !((location ^ (location >> 1)) & 1) ? HIGH : LOW);

      return true;
    }

    void moveUp() {
      info("moveUp()");
      stopMoving();
      setFailSafe();
      movingUp = true;
    }

    void moveDown() {
      info("moveDown()");
      stopMoving();
      setFailSafe();
      movingDown = true;
    }

    void moveTo(int _target) {
      info("moveTo(_)");
      stopMoving();
      setFailSafe();
      moveToTarget = true;
      target = _target;
    }

    void stopMoving() {
      info("stopMoving()");
      movingUp = false;
      movingDown = false;
      moveToTarget = false;
      STEPPER_OFF;
    }


  protected:
    const unsigned long FAILSAFE_MS = 1000 * 60 * 5; // 5 minutes max time running the motor

    unsigned long failsafe = 0;
    unsigned long lastMove = 0;
    boolean movingUp = false;
    boolean movingDown = false;
    boolean moveToTarget = false;
    int target = 0;

#ifdef DEBUG
    void _info(const char *s) {
      Serial.print(name);
      Serial.print(": ");
      Serial.println(s);
    }
#endif

    void setFailSafe() {
      failsafe = millis();
    }

    boolean tripFailsafe() {
      if (millis() - failsafe < FAILSAFE_MS) return false;
      if (!movingUp && !movingDown && !moveToTarget) return false;
      stopMoving();
      return true;
    }

};

That code is way more advanced than any other stepper motor sketches I have. Well done !