converting ascii to decimal for numbers greater than 9

Hey guys,

I'm trying to enter a number 0-12 in the serial monitor and store that number is two variables. If the number is 0-9, the first variable will have a "0", the second will have 0-9 depending on the number entered. For example, if I enter 11, both variables should be "1". And if I enter 12, the first should be "1", second "2", etc.

Since I'm reading (serial.read()) the numbers I'm entering in the serial monitor, the value of that number is being stored as an ascii value. This is fine for single digit numbers since I can just use the ascii codes for 1, 2, etc but I don't know what to do for numbers with more than 1 digit (10,11 and 12).

Is there a better way of doing this than using the ascii codes?

Here's the relevant code I'm using:

int h; 
int a;
int b; 

void setup() {
  Serial.begin(9600);
  Serial.print("Enter Hour:  ");
}


void loop() { 

if (Serial.available()) {

h = Serial.read(); 
Serial.print("\n");
Serial.print(h);

}


if (h > 48 && h < 58) {
if (h==49) {a=0; b=1;} // if h == 1
if (h==50) {a=0; b=2;} // if h == 2
if (h==51) {a=0; b=3;} // if h == 3
if (h==52) {a=0; b=4;} // if h == 4 
if (h==53) {a=0; b=5;} // if h == 5
if (h==54) {a=0; b=6;} // if h == 6
if (h==55) {a=0; b=7;} // if h == 7
if (h==56) {a=0; b=8;} // if h == 8
if (h==57) {a=0; b=9;} // if h == 9

if (h==10) {a=1; b=0;}
if (h==11) {a=1; b=1;}
if (h==12) {a=1; b=2;}  
Serial.print("|A:");Serial.print(a);Serial.print("|");
Serial.print("|B:");Serial.print(b);Serial.print("|");
}}

subtract '0' from the char and it gives you it's actual value. You also need to loop through all the characters, multiplying the value you have so far, by 10 before you add the new digits value.

int h; 
int a;
int b; 

void setup() {
  Serial.begin(9600);
  Serial.print("Enter Hour:  ");
}

void loop() { 
int total=0;
while (Serial.available()>0) 
  {h = Serial.read();
   if(h >= '0' &&  h<='9')
      total=total*10 + (h-'0');
    Serial.print(h);
   } 
Serial.print(total,DEC);
}

If you read all the digits into a null-terminated char array (a string with a small s) you can use the atoi() function.

Some examples in this demo

...R