My project is to make a motor move at a certain speed and to a certain position. I am using the accelstepper library to control the motor. I know how to make it work if I put the speed and the position in the code, but what I want is to make them variables and the user enters the value for the speed , distance, and acceleration they want, using the serial monitor. I know how to do this in C++ using cin, but here when I use Serial.read(), it just doesnt work and one value entered by the user goes to all the variables. The motor moves when i put the values of the speed, distance, acceleration in the code, but when i ask the user to put it, it doesnt move.
can you please help?
Also if there is a good book or online source about serial communication or accelstepper, Ill be grateful if you can point me to it.
Thank you so much,
here is my code:
#include <AccelStepper.h>
AccelStepper motor(1,2,3); // step pin = 2 dir pin = 3
char mode; // 1 for forward, 2 for backward
double velocity;
double distance;
double acceleration;
void setup()
{
Serial.begin(9600);
Serial.println("Please choose a number for the desired mode:");
Serial.println("1) forward");
Serial.println("2) backward");
}
void loop()
{
if(Serial.available())
{
mode=Serial.read();
Serial.println(mode);
if (mode=='1') //also tried if mode ==49
{
Serial.println("you have chosen forward"); //prints "you have chosen forward" but motor doesnt move,
Serial.println("enter speed");
velocity=Serial.read();
Serial.println("enter acceleration");
acceleration=Serial.read();
Serial.println("enter distance");
distance=Serial.read();
motor.setCurrentPosition(0);
moveup();
}
if (mode=='2')
{
Serial.println("you have chosen the backward mode");
Serial.println("enter speed");
velocity=Serial.read();
Serial.println("enter acceleration");
acceleration=Serial.read();
Serial.println("enter distance");
distance=Serial.read();
motor.setCurrentPosition(0);
movedown();
}
}
}
void moveup()
{
while(mode==1)
{
motor.setMaxSpeed(velocity);
motor.setAcceleration(acceleration);
motor.moveTo(-distance);
motor.run();
}
}
void movedown()
{
while(mode==2)
{
motor.setMaxSpeed(velocity);
motor.setAcceleration(acceleration);
motor.moveTo(distance);
motor.run();
}
}