I'm with some trublle using stepper mottor

well, i'll put my code bellow.

the problem that i've been leading is that i can't make my stteper mottor go back to the last position, that's why i set "position = 0".

#include <Stepper.h>

const int stepsPerRevolution = 2048;  // change this to fit the number of steps per revolution
char abrir;
int position = 0;
// ULN2003 Motor Driver Pins
#define IN1 13
#define IN2 12
#define IN3 14
#define IN4 27

// initialize the stepper library
Stepper myStepper(stepsPerRevolution, IN1, IN3, IN2, IN4);

void setup() {
  // set the speed at 5 rpm
  myStepper.setSpeed(5);
  // initialize the serial port
  Serial.begin(9600);
}

void loop() {
  
 while (Serial.available() > 0) {
        abrir = Serial.read();

        if (abrir == '1' || abrir == '2') {
            break;
        }
    }

    // Se enviado "1" pelo monitor serial a Janela deve abrir //
    if (abrir == '1' && position == 0) {
        abrir = '0';

        Serial.println("Janela aberta");

        for(int i = 0; position<=5; i++);

  {
    myStepper.step(450);
    delay(20);
        }
    }
    // Se enviado "2" pelo monitor serial a Janela deve fechar //
  while (Serial.available() > 1)
  if (abrir == '2' && position == 5) {
        abrir = '0';

        Serial.println("Janela aberta");

        for(int i = 5; position<=0; i++);

  {
    myStepper.step(450);
    delay(20);
        }
  }
  }

how you see, i set the where my motor has to go, and the stepps...but it's not happen.

hi

  1. What do you want to do with this line: (line 46),
    while (Serial.available() > 1)?

  2. Remove ";" from the end of the lines:
    for(int i = 0; position<=5; i++); (line 38).
    for(int i = 5; position<=0; i++); (line 52).

  3. I didn't understand the logic of using the "position" variable in these 2 "for",
    please explain.

Your topic has been moved to a more suitable location on the forum. Introductory Tutorials is for tutorials that e.g. you write, not for questions. Feel free to write a tutorial once you have solved your problem :wink:

I don't see the 'position' variable being changed anywhere. If it is being increased/decreased, you should have something like:

(line 38)

for (position = 0; position <=5; position++)
{
  //forwards steps
}

and

(line 52)

for (position = 5; position >=5; position--) 
{
//backwards steps
}

Your code does not increase or decrease the position variable, which I presume you will use to track the position of the stepper motor. Also, your second for loop, if it worked, would continue increasing, which in this case I'm pretty sure you would not want.

When you modify the code, if you want the stepper to step backwards, where it says:

myStepper.step(450);

replace with

myStepper.step(-450);

Hope this helps.

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