Servo Control

Hi all,

I am trying to control a servo to go from 10 to 170 degrees then back to 10 degrees and stop at that position. I find that either the servo will just keep moving constantly between these two positions or if i add servo.detach command it will stop after one full cycle of what i want it to do! but then i dont know how to reattach it.

Essentially i would like to press a specific keyboard key say ‘r’ and the servo would go through one cycle and stop, if i then pressed that ‘r’ key again it would go through another cycle then stop.
Is there anyway to use the ‘r’ key as a virtual push button so that when its pressed its HIGH and the servo moves and when its LOW(unpressed) the servo stops?

Any other ideas are also appreciated

Thanks

Servo_position_control.ino (1.15 KB)

I’m not familiar with the serial.available()-function but I believe it cannot be used like You did in Your code. I would try changing the while-statement to an if-statement. I have not tested this so I may be wrong.

void loop() {
  
  
  Serial.println("Press Any Key To Rotate Servo") ; // prompts for input
   if (Serial.available ()) { // Starts the servo if a key press is recognised 
  
   
 for (pos=10; pos<=100 ; pos=pos+1) { // moves servo until desired position is reached
  
    myPointer.write(pos); // send servo to pos
    delay(servoDelay); // 
    
   } 
  
  delay(1000); // sets a delay at the bottom after the switch has been activated
  
  for (pos=100; pos>=10 ; pos=pos-1) { // moves servo until desired position is reached
    
    myPointer.write(pos); // send servo to pos
    delay(servoDelay); // 
    
    }
    }

}

If You want the servo to start with pressing some specific button, then You have to read the pressed key into a string variable and then use that variable to make things happen. Study the SerialEvent-example in the Arduino IDE, it should give You all answers.

You check if there is a character available, but you never read any characters so there will always be characters in the input buffer.

At the very least you should read all the available characters to empty the buffer.

Have a look at serial input basics for simple reliable ways to receive data.

...R