Input "acceleration" using serial monitor

Hello,
I am working on a project in which I need to input the value using the serial monitor and use that value as the acceleration for a motor. The motor is supposed to rotate when I press a push button which is connected to pin 9. But for some reason, it's not working the way it should. I have attached the code below

  #include <AccelStepper.h>
AccelStepper stepper1(1, 6, 12);
byte counter = 0;
long vel = 5000;
int steps_f = 30;
int steps_i = 0;

void setup()
{  
  stepper1.setMaxSpeed(vel);
 Serial.begin(115200);
 pinMode(9,INPUT);
  Serial.println("Setup");
}

void loop() {
while (Serial.available() > 0) {   
    long acc = Serial.parseInt(); 
    Serial.println(acc);
    if( digitalRead(9) == HIGH)
  {
    Serial.print("Hitting ");
          stepper1.setAcceleration(acc);
          stepper1.runToNewPosition(steps_f);
          stepper1.runToNewPosition(steps_i);
          stepper1.runToNewPosition(steps_f/3);
          stepper1.setAcceleration(acc/1.5);
          stepper1.runToNewPosition(steps_f);
  }
}
}

Also, when I remove the while statement and declare "acc" the motor works fine with the push button.

Any help would be much appreciated, thanks.

Connect the push button between pin 9 and GND, and change

pinMode(9,INPUT);

to
pinMode(9,INPUT_PULLUP);

I tried doing that, it did not help. Thanks though

Also, I think the way it is set up is alright (since it works until I add the serial monitor input into the code). I think that my code is incorrect.

I can see one problem, which is that these lines

Serial.print("Hitting ");
stepper1.setAcceleration(acc);
stepper1.runToNewPosition(steps_f);
stepper1.runToNewPosition(steps_i);
stepper1.runToNewPosition(steps_f/3);
stepper1.setAcceleration(acc/1.5);
stepper1.runToNewPosition(steps_f);

are only executed while there is data in the Serial buffer. You should split up the code:
1: check for Serial data and put it in a variable
2: check if the button is pressed
3: if one or both is/are true, if yes then run the code to start the motor

PS.: When using INPUT_PULLUP, did you change

if(digitalRead(9) == HIGH)

to

if(digitalRead(9) == LOW)

??

Pay attention to the floating input issue when using button

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

...R

My tutorial on Multi-tasking in Arduino has detailed stepper example using AccelStepper which includes entering a float value from the Serial monitor without blocking the loop
That tutorial also covers other important details on how to run a stepper and do other stuff at the same time

The comment on button input should be noted. The link contains a further link button debounce.
My library for button debounce is here.

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