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.
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
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.
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