Stop moving servo motor by serial monitor

Hello everybody,

I want to move the servo motor if I write 'a' in the serial monitor , and when I write 's' I want that it stops moving and still in the last position.

You can check the sketch that I wrote but it's not working,when I press 'a' the servo still moving until 180,it doesn't stop when I press 's'.

the sketch:

#include <Servo.h>

Servo servoUp;

int pos = 0;

char reading = 0;

void setup() {
Serial.begin(9600);
servoUp.attach(11);
}

void loop() {

servoUp.write(pos);

while (Serial.available()) {
reading = Serial.read();

if ( reading == 'a' && reading != 's'){
while(pos <180 ){
servoUp.write(pos);
pos++;
delay(40);

}
}
servoUp.write(pos);
}
}

Thank you for helping in advance.

You can check the sketch that I wrote but it's not working,when I press 'a' the servo still moving until 180,it doesn't stop when I press 's'.

When you enter a letter, it is checked. If it is 'a'. this is what happens:

        while(pos <180 ){
          servoUp.write(pos);
          pos++;
          delay(40);
         
      }

Nothing in there cares that you might be pounding keys, yelling at the PC, sweating bullets, etc. If you expect something you do to matter, you MUST revise this loop. You could see if there is data to read, and peak() at the next character if there is. If that character is an 's', break out of the loop.

void loop() {

servoUp.write(pos);

while (Serial.available()) {
reading = Serial.read();

if ( reading == 'a' && reading != 's'){
for(pos = start ; pos <180 ; pos++ ){
servoUp.write(pos);
if(reading == 's'){
continue;
}
delay(40);
}
}
start = pos;
servoUp.write(pos);
}
}

I wrote this code but the same problem :frowning:

but the same problem

Because you haven't changed anything. The for loop is simply a variation of the while loop you were using before.

Suppose I create a function, called userWantsToStop(). Suppose I call it, in the while loop:

   while(pos <180 )
   {
          servoUp.write(pos);
          pos++;
          delay(40);
          if(userWantsToStop())
             break;      
   }

Can you see how that would cause the loop to end?

Can you imagine what would have to happen in the userWantsToStop() function, so that it could return true (the user wants to stop) or false (no, the user is perfectly happy letting the servo continue moving)? I think I gave you enough hints in my previous reply.

yes ^^ , it works now, thank you ^^

If you are planning a more complex program it would be much better not to control the servo with a FOR loop. Look at how the control is managed without blocking in several things at a time.

...R