So I decided to alter some code I found online for driving servos to something more user friendly. The initial code dealt with a char array hardcoded into the sketch. For every 'f' the servos would go forward for 200ms, for every 'b' backwards for 200ms, for every 'l' left for 200ms, for every 'r' right for 200ms, and for 's' just stop completely. I decided to recode this so that it drives based on user input to Serial. This current code works, however there is a strange delay I found. I can send any string of characters I want into Serial, and it will perform as expected, but only after waiting around 10-15 seconds. The code just does nothing for 10-15 seconds in the beginning when you send a character to Serial, but then it works perfectly. Then after that, I don't think it will do anything if you try to send more characters a second time (probably has to do with 's' stopping it, but that is my second bug to handle). Anyone see anything strange in the code that could cause for this? Here is my current code:
#include <Servo.h> //include servo library
Servo servoLeft; //declare servo objects
Servo servoRight;
void setup() {
servoLeft.attach(13); //attach left servo to pin 13
servoRight.attach(12); //attach right servo to pin 12
Serial.begin(9600); //begin Serial at 9600 baud
char maneuvers[] = {Serial.read()}; //read incoming characters and write to maneuvers[] array
int index = 0; //initialize index as int at 0
do {
go(maneuvers[index]); //use go() function each time through index of maneuvers[] while 's' is not read in the index of maneuvers[]
} while (maneuvers[index++] != 's');
}
}
void loop() {
}
void go(char c) { //go() takes 1 parameter of a char
switch(c) {
case 'f':
servoLeft.writeMicroseconds(1700); //in the case of 'f' drive both servos forward
servoRight.writeMicroseconds(1300);
break;
case 'b':
servoLeft.writeMicroseconds(1300); //in the case of 'b' drive both servos backward
servoRight.writeMicroseconds(1700);
break;
case 'l':
servoLeft.writeMicroseconds(1300); //in the case of 'l' drive servos left
servoRight.writeMicroseconds(1300);
break;
case 'r':
servoLeft.writeMicroseconds(1700); //in the case of 'r' drive servos right
servoRight.writeMicroseconds(1700);
break;
case 's':
servoLeft.writeMicroseconds(1500); //in the case of 's' stop both servos
servoRight.writeMicroseconds(1500);
break;
}
delay(200); //do everything for 200ms after break in case
}