I have a very basic question that is doing my head in. I have keypad (0-9 plus * #).
The library return me a char which equals the pressed button which works perfectly well.
I need to be able to convert the char into a int so that I can assign an array variable according to the pressed number.
eg: array[pressed button number here]
This should be simple with toInt() function from my understanding but I cannot get it working. Here is some simple code that also doesn't work. Can anyone advise why?
int x; //this needs to be the integer value of str
char str;
void setup() {
}
void loop() {
str = "7"; //assign a number to the string variable
x = str.toInt();
}
I receive this error on compiling:
exit status 1
request for member 'toInt' in 'str', which is of non-class type 'char'
There are different ways that data can be represented and each way has functions to handle the data. Here are ways to change a character ('0' - '9') to a number (0 - 9) and a string ("7") to a number (7).
int x; //this needs to be the integer value of str
char chr = '4'; // declare a char
char str[] = "7"; // declare one character string (+ 1 for the null terminator (2 bytes total))
void setup()
{
Serial.begin(115200);
x = chr - '0'; // to get the number (0-9) from a character subtract '0' or 48 (dec) or 0x30 (hex)
Serial.print("char chr converted to a number = ");
Serial.println(x);
Serial.print("string str converted to a number = ");
Serial.println(atoi(str));
}
void loop()
{
}
Thank you for the help. I was trying to use string and could not make this work until I realised (super Noob) that the declaration should be String not string and i had my case wrong.
Once I did that then I was able to convert using toInt()
Thanks again.