Servo Problem

#include <Servo.h>

Servo servo1;

void setup()
  servo1.attach(14); //analog pin 0

void loop() 
  // Convert serial input to integer
  if( Serial.available())
    char carray[4];
    // Go through each character and add it in
    int cnt = 0;
    while ( Serial.available()) 
      carray[cnt] =;
    carray[3] = 0;  // Null termination


I’m trying to write a program that does the following: The user inputs a number between 0 and 180 in the serial monitor. Once they send it, the array of characters is converted to a number and sent to the servo. If I type in any number (i.e. 180), only the value of the last character is sent (i.e. 0). I replaced ‘atoi(carray)’ with a literal 180 and it worked just fine. I printed out the results of atoi(carray) using Serial.print() and I got the number 180. What’s going wrong here? Why is only the last character being sent to the servo?

Try the below servo test code:

// zoomkat 10-4-10 serial servo test
// type servo position 0 to 180 in serial monitor
// for writeMicroseconds, use a value like 1500
// for IDE 0019 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() {
  myservo.writeMicroseconds(2000); //set initial servo position if desired
  myservo.attach(7);  //the pin for the servo control 
  Serial.println("servo-test-21"); // so I can keep track of what is loaded

void loop() {

  while (Serial.available()) {
    if (Serial.available() >0) {
      char c =;  //gets one byte from serial buffer
      readString += c; //makes the string readString

  if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string 
    int n;
    char carray[6]; //converting string to number
    readString.toCharArray(carray, sizeof(carray));
    n = atoi(carray); 
    myservo.writeMicroseconds(n); // for microseconds
    //myservo.write(n); //for degees 0-180

I'd need to see your code with the serial.prints in it to be sure, but it looks as though you're having the usual trouble with serial.available. Serial comms is very slow compared to the speed ofthe arduino, so when the first character arrives, it gets read and then, while the second character is being sent, the arduino sees that nothing is available and sends the atoi of the carray with a single char to the servo. Then it does the same with the second & third character. This happens rapidly in a human frame of reference, so all you see is that the 0 char went to the servo.

Spot on Bill! I put in a check to wait until there were 3 characters. Works like a charm. Thank you!