Servo control on serial monitor

Hi, I would like to control my servo; on and off using serial monitor. The servo should rotate to and fro continuously if I press 'a' it should go on and should turn off if I press 'b'. When I execute the code it only runs once and then stops. Please help me with this.

Many thanks

What code?

#include <Servo.h>
Servo myservo;
int pos = 0;
int a=0;
int incomingByte=0;
void setup()
Serial.print("ready ");

void loop()
{ if (Serial.available() > 0)
{ incomingByte =;

for(pos = 0; pos <= 90; pos += 1) 
for(pos = 90; pos>=0; pos -=1)     


Why test it?
What other value could it have?

Why not test the character you just received?

Please remember to use code tags when posting code.

Sorry I didn't understand you

You've just set the variable 'a' to 1.
And then you test it, to see if it equals 1.


I am a noob so you will see some logical mistakes :smile:

I'd turn the code around.
Lose the for loops, and make the servo movement conditional on a single Boolean which is set true if you receive 'a' and false if you receive 'b'.

So is it like, Use an if condition?

Hello @kryon07 ,

Your post was MOVED to its current location as it is more suitable.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

In particular the parts on corrects posting code and choosing the right section to post your question.