Servo controlled with keyboard

I am fairly new to arduino and I was wondering if there was any way that I can control a servo with a keyboard I have been trying to find some sources online but I haven't had much luck

1 Like

You haven't found zoomkat's code yet?
He'll be along in a moment.

no I haven't found zoomkat's yet can you send me a link to it

The below servo test code uses the pc keyboard keys. Type the desired servo position in the serial monitor text box, then send the position to the arduino. If you want to use keys like the up, down, left, and right keys to move the servo, you will need another application on the pc to perform those actions.

// zoomkat 10-22-11 serial servo test
// type servo position 0 to 180 in serial monitor
// or for writeMicroseconds, use a value like 1500
// for IDE 0022 and later
// Powering a servo from the arduino usually *DOES NOT WORK*.

String readString;
#include <Servo.h> 
Servo myservo;  // create servo object to control a servo 

void setup() {
  Serial.begin(9600);
  myservo.writeMicroseconds(1500); //set initial servo position if desired
  myservo.attach(7, 500, 2500);  //the pin for the servo control, and range if desired
  Serial.println("servo-test-22-dual-input"); // so I can keep track of what is loaded
}

void loop() {
  while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString
    delay(2);  //slow looping to allow buffer to fill with next character
  }

  if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string 
    int n = readString.toInt();  //convert readString into a number

    // auto select appropriate value, copied from someone elses code.
    if(n >= 500)
    {
      Serial.print("writing Microseconds: ");
      Serial.println(n);
      myservo.writeMicroseconds(n);
    }
    else
    {   
      Serial.print("writing Angle: ");
      Serial.println(n);
      myservo.write(n);
    }

    readString=""; //empty for next input
  } 
}
1 Like

thanks for the code and do you know of any programs that will allow me to use my arrow keys

There are various programming languages that can take keyboard key status input and that can support serial port operations. You will need to look for one that matches your level of programming experience.