0

SOLVED:

You can change the char buffer by using:

char *arg;
arg = SCmd.next();
int i;
sscanf(arg, "%d", &i);
Serial.print("String value "); 
Serial.println(arg); 

Serial.print("Integer value "); 
Serial.println(i); 



PROBLEM:

I can't seem to figure out how to change a char buffers contents to an integer from a stored string.

For instance:

'1' should be 1,

'121' should be 121

Here's what I tried.

void doIt()
{
  char *arg;
  arg = SCmd.next();    // Get the next argument from the SerialCommand object buffer

  if (arg != NULL)      // As long as it existed, do it
  {
    int argInted = (int)arg; // Cast char arg* -> int argInted.

    Serial.print("String value "); 
    Serial.println(arg); 

    Serial.print("Integer value "); 
    Serial.println(argInted); // Print this new found integer.
  } 
  else {
    Serial.println("Fix your arguements"); 
  }
}

Here's what I get, it evaluates to 371 every time. I'm storing different things in the pointer buffer though, any ideas on how to convert?

Arduino Ready
> INPUT 1
String value 1
Integer value 371
> INPUT 2
String value 2
Integer value 371
> INPUT WHATSthisDO
String value WHATSthisDO
Integer value 371
b__
  • 21
  • 1
  • 6

2 Answers2

0

For converting a char* to int use atoi() function. http://www.cplusplus.com/reference/cstdlib/atoi/

Andro
  • 2,232
  • 1
  • 27
  • 40
0

To cite WhozCraig: That isn't how you convert a char* to an int

A simple cast doesn't do because a char is 1 byte and an int is 4 byte, so the remaining 3 bytes can contain any garbage leading to unpredictable results:

char s[1] = {'2'};

cout << s << endl;
cout << (int)s << endl;
cout << atoi(s) << endl;

leads on my machine to

2
-5760069
2
Pavel
  • 7,436
  • 2
  • 29
  • 42