Converting a part of a string to int

I am working on something where I use Spark.function() to pass a string to a function, the string can look like this 1-10-500 or 1-3-1000 or even 1-4-43209 or something completely different…

In the string I set pin-[state/pulses]-delay

Pin can go from 0 to 7.
State can be 0 or 1 when no delay is set, or from 1 to pretty much everything when a delay is set.
Delay can go from 1 to also almost everything.

When no delay is set, a string like “1-1” would set pin 1 high, and “2-0” would set pin 2 low.
If the delay is added like “1-10-500” pin 1 will make a pulse 10 times, with 500ms delay.

My problem now is that I have problems getting the pin number, the state number and the delay number out of the string and into an integer. Are there anyone who can help me with that?

Mikey, to parse your string arguments take a look at this topic. Once you have your substrings, you can convert them to integer using the atoi() command as follows:

atoi(char * p);  where char * p is the pointer to your array of chars to convert

In the topic I refer to, the strtok() function is used for parsing the string using a seperator which in your case is “-”. For each field parsed, p points to the parsed char array so to get the integer value you would use:

val = atoi(p);

Le me know how it goes! :smile:

1 Like

Gave this a shot, still getting an error

int handlePinCommand(String command)
    int pinNum = 0;
    int pinState = 0;
    int pinDelay = 0;
    char * p = strtok(command, "-");
    int commandStep = 0;
    while (p != NULL)
        //get the values for 
        if (commandStep == 0)
            pinNum = atoi(p);
        else if (commandStep == 1)
            pinState = atoi(p);
        else if (commandStep == 2)
            pinDelay = atoi(p);
        p = strtok(NULL, "-");

and the error is

In file included from ../inc/spark_wiring.h:30:0,
from ../inc/application.h:31,
from dht22_temperature.cpp:2:
../../core-common-lib/SPARK_Firmware_Driver/inc/config.h:12:2: warning: #warning "Defaulting to Release Build" [-Wcpp]
dht22_temperature.cpp: In function 'int handlePinCommand(String)':
dht22_temperature.cpp:103:35: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'
make: *** [dht22_temperature.o] Error 1

Mikey, now that I see a bit more of your code, I see you need to convert the string to an array of chars first. Again, referring to the topic I pointed to, you need to add this at the top:

char * params = new char[command.length() + 1];

strcpy(params, command.c_str());

The first command creates a new char array of the same length as String “command”. Since strtok() is destructive, strcpy() is used to copy the array of chars from the String to the “params” array of chars just created. The rest should work just fine except that you need to change:

char * p = strtok(command, "-");
to char * p = strtok(params, "-");

1 Like

Thank you! Seems to work! :smiley:

1 Like