I have this code, and i'm trying to control the motor speed(0, back(- num), forward( num)), with putting numbers in the serial monitor but after the first number its not letting me enter new number:
int half_step[8] = {1, 3, 2, 6, 4, 12, 8, 9};
int idx = 0;
int motorSpeed = 5; // Default motor speed (in milliseconds)
int currentSpeed = 0; // Current speed setting
int newSpeed =0;
int newvalue = 0;
void setup() {
Serial.begin(115200);
Serial.setTimeout(2);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
digitalWrite(8, 0);
digitalWrite(9, 0);
digitalWrite(10, 0);
digitalWrite(11, 0);
}
void loop()
{
while (Serial.available()&& newvalue == 0)
{
newvalue = 1;
newSpeed = Serial.parseInt();
Serial.read();
Serial.println(newSpeed);
if (newSpeed == 0 && newvalue==1)
{
Serial.println("if enter 0:");
Serial.println(newSpeed);
stopMotion();
newvalue=0;
}
else if(currentSpeed != newSpeed && newvalue ==1)
{
Serial.println("if enter not the same:");
currentSpeed = newSpeed;
newvalue = 0;
Serial.println(currentSpeed);
setMotorSpeed(currentSpeed, newvalue);
}
}
}
void setMotorSpeed(int currentSpeed,int newvalue)
{
Serial.println(currentSpeed);
motorSpeed = abs(currentSpeed); // Set the speed (positive value)
int direction = (currentSpeed > 0) ? 1 : -1; // Determine the direction
while (currentSpeed == newSpeed && newvalue == 0)
{
Serial.println("while:");
Serial.println(currentSpeed);
PORTB = half_step[idx];
delay(motorSpeed);
idx += direction;
if (idx > 7) idx = 0;
if (idx < 0) idx = 7;
Serial.println(newvalue);
}
}
void stopMotion()
{
currentSpeed = 0;
motorSpeed = 0;
PORTB = 0;
Serial.println("Motion stopped");
newvalue=0;
}