So I was making a little autonomous robot that reacted to things and drove around based on sensor input. I am using continuous rotation servos as wheel motors to accomplish this. I wanted to play around with different motor speeds and found it rather tiresome to continually hardcode in different speeds for each servo, so I decided I would make a little program that took the value entered into serial monitor and used it as the value I wanted to set my servo speeds to. For those unfamiliar with continuous rotational servos, they take modulated pulse widths (in spacing of microseconds) to determine the rotational direction and velocity of the motor. 1300µS = full speed counter clockwise, 1500µS = complete stop, 1700µS = full speed clockwise. Obviously the values in between full speed and stop behave linearly in terms of speed (i.e. 1400µS = 50% speed counter clockwise). Anyways, here was my loop code:
void loop() {
Serial.print("Send an integer value between 1300 and 1700 ");
Serial.println("microseconds to test speed...");
while (Serial.available() == 0); //Continue loop once serial.available > 0
pulseWidth = Serial.read(); //Set read value to pulse width
if (pulseWidth >= 1300 && pulseWidth <= 1700) { //set limitations to valid values (anything < 1300 or > 1700 will do nothing to the servo)
Serial.println("Testing speed at: ");
Serial.println(pulseWidth);
leftServo.writeMicroseconds(pulseWidth); //rotate both servos at this speed for 6 seconds
rightServo.writeMicroseconds(pulseWidth);
delay(6000);
leftServo.writeMicroseconds(1500); //stop both servos completely, loop resets if satisfied
rightServo.writeMicroseconds(1500);
}
else {
Serial.println("Error: value cannot be read"); //Anything < 1300 or > 1700 gets error message, loop resets
}
}
I was confused as to why I was plugging in values to serial monitor that satisfied the conditions of the first if statement but kept getting 4 error messages immediately. Then I realized I stupidly coded this to read individual characters, hence the 4 error messages because obviously all numbers 1-9 are < 1300... Anyway I remembered reading about a situation like this in an arduino book and how to go about doing this so it works, however I can't seem to find the section of the book... I know I can just turn the pulseWidth variable value into a string object using String, but can't seem to remember how and if I can read the whole string in the serial monitor. And if so, how do I revert it back to int form so it can be read by the Servo.writeMicroseconds() variable? Can I use two variables, set 1 to the input string and then set the second variable as the non string value of 1st or something of the like? Anyone have any help or better suggestions?