6

I receive some data in a char variable, and the result in teststring is always a number. How can I convert this number to a variable int?

After that I can put the int variable on delay time. There is a piece of my code:

String readString = String(30); String teststring = String(100); int convertedstring; teststring = readString.substring(14, 18); (Result is 1000) digitalWrite(start_pin, HIGH); delay(convertedstring); // Result of teststring convert digitalWrite(start_pin, LOW); 

3 Answers 3

7

Use:

long number = atol(input); // Notice the function change to atoL 

Or, if you want to use only positive values:

Code:

unsigned long number = strtoul(input, NULL, 10); 

Reference: http://www.mkssoftware.com/docs/man3/atol.3.asp

Or,

int convertedstring = atoi(teststring.c_str()); 
Sign up to request clarification or add additional context in comments.

5 Comments

Error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'
That's my try: long number = atol( teststring );
It-s working! int convertedstring = atoi(teststring.c_str()); Tnk you
0

String to Long Arduino IDE:

 //stringToLong.h long stringToLong(String value) { long outLong=0; long inLong=1; int c = 0; int idx=value.length()-1; for(int i=0;i<=idx;i++){ c=(int)value[idx-i]; outLong+=inLong*(c-48); inLong*=10; } return outLong; } 

1 Comment

What do you mean by "String to Long Arduino IDE"?
0

Do you have access to the atoi function in your Arduino environment?

If not, you can just write some simple conversion code in there:

int my_atoi(const char *s) { int sign=1; if (*s == '-') sign = -1; s++; int num = 0; while(*s) { num = ((*s)-'0') + num*10; s++; } return num*sign; } 

1 Comment

Looks like you might have a bug where the pointer s is always incremented even when the first character is not '-'?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.