String to int

Trying to change a string to an integer like this:

String str1 = "13";
int num1 = int(str1);

But this will return 442 but I want 13.

You need to use the toInt method of the String class

Ah, thanks, now I do remember reading that of the c++ website.

If you were to use a C character array then you'd probably want to use atoi() --ascii to integer function. casting to int just gets you format values. Me, I look at each character as it comes in without buffering when memory is tight. Error handling can fatten the code no matter which path you take. And even with perfectly clean data, serial i/o isn't perfect. I do wonder with AVR-C if including a library brings the whole thing in or just the parts you need in your program? Hey... it's a matter of optimization.

I do wonder with AVR-C if including a library brings the whole thing in or just the parts you need in your program?

Including a library only causes the necessary functions to be linked in.

Code for testing servos which includes converting a numerical string into an integer (0022 IDE).

// 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(2000); //set initial servo position if desired
  myservo.attach(7);  //the pin for the servo control 
  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
  } 
}

PaulS:

I do wonder with AVR-C if including a library brings the whole thing in or just the parts you need in your program?

Including a library only causes the necessary functions to be linked in.

sweet!