I'm trying to read information from the keyboard via the Serial.read function, but i cant figure out the proper variable type. I want to be able to say "Hey user! Tell me the angle of the servo!". Right now I've been using int pos =Serial.read(); and I'm getting odd numbers.
How can I get "20" when I type "20" on the keyboard?
Your call to to Serial.read() returns an integer value of each ASCII character you send down the serial port from the Arduino IDE. For a table of the corresponding numeric values of each character, see this page.
So, if you type "20" in the serial monitor window, successive calls to Serial.Read() will return the numbers 50 then 48. Your program then needs to unravel those values and convert them back into an integer value.
You will also need to first check to see when input is available on the serial port input, via Serial.available().
Below is the code ive got so far. Sadly the math is wrong once i get into triple digits. Any idea why?
void loop()
{
long total = 0;
int pos =0;
int figure =0;
// read the sensor:
if (Serial.available() > 0)
{
delay(15); //delay so it has time to read all in buffer
int av = Serial.available();
Serial.print(av);
Serial.println(" bytes are availible");
for (int counter = 0; counter < av; counter++)
{
pos = Serial.read();
Serial.print("At position ");
figure=av-1-counter;
Serial.print(figure);
Serial.print(" you said pos = ");
pos=pos-48;
Serial.print(pos);
long temp = pow(10,figure);
Serial.print ("(temp = ");
Serial.print (temp);
Serial.print (")");
total = total+pos*temp;
Serial.print(" Totaling ");
Serial.println(total);
}
}
}
You shouldn't use pow() for an operation like this, because pow() is a floating point library function and, as such, consumes a lot of resources and can introduce inaccuracies. Fortunately, you don't need it. Try something like the below instead. Also, instead of
pos=pos-48;
it's much clearer to write the equivalent
pos=pos-'0';
or, more concisely still
pos -= '0';
void loop()
{
long total = 0;
int pos = 0;
int figure = 0;
// read the serial port:
if (Serial.available() > 0)
{
delay(15); //delay so it has time to read all in buffer
int av = Serial.available();
Serial.print(av);
Serial.println(" bytes are available");
for (int counter = 0; counter < av; counter++)
{
pos = Serial.read();
Serial.print("At position ");
figure = av-1-counter;
Serial.print(figure);
Serial.print(" you said pos = ");
pos -= '0';
Serial.print(pos);
total = 10 * total + pos;
Serial.print(" Totaling ");
Serial.println(total);
}
}
}