Servo code using characters sent via the serial monitor. For using simple keyboard key presses, you will need to make an application for the pc to capture the key strokes and send them out the serial port.
// zoomkat 11-14-11 serial servo test
// type servo position 1f, 1r, xx, etc. in serial monitor and enter
// Powering a servo from the arduino usually DOES NOT WORK.
String readString;
#include <Servo.h>
Servo myservo1; // create servo object to control a servo
Servo myservo2;
void setup() {
Serial.begin(9600);
myservo1.writeMicroseconds(1500); //set initial servo position if desired
myservo2.writeMicroseconds(1500); //set initial servo position if desired
myservo1.attach(6); //the pin for the servo control
myservo2.attach(7);
Serial.println("servo-test-22"); // 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); // allow buffer to fill with next character
}
if (readString.length() >0) {
Serial.println(readString); //so you can see the captured string
if (readString == "1f") myservo1.writeMicroseconds(2000);
if (readString == "1r") myservo1.writeMicroseconds(1000);
if (readString == "1x") myservo1.writeMicroseconds(1500);
if (readString == "2f") myservo2.writeMicroseconds(2000);
if (readString == "2r") myservo2.writeMicroseconds(1000);
if (readString == "2x") myservo2.writeMicroseconds(1500);
if (readString == "xx"){
myservo1.writeMicroseconds(1500);
myservo2.writeMicroseconds(1500);
}
if (readString == "ff"){
myservo1.writeMicroseconds(2000);
myservo2.writeMicroseconds(2000);
}
if (readString == "rr"){
myservo1.writeMicroseconds(1000);
myservo2.writeMicroseconds(1000);
}
readString=""; //empty for next input
}
}