c++microcontrollersparkcore

Trying to properly substring with String


Given the following function:

If I execute setColor("R:0,G:0,B:255,");

I'm expecting the red, grn, blu values to be:

0 0 255 except I'm getting 0 0 0

It's working fine for R:255,G:0,B:0, or R:0,G:255,B:0, though.

int setColor(String command) {

    //Parse the incoming command string
    //Example command R:123,G:100,B:50,
    //RGB values should be between 0 to 255
    int red = getColorValue(command, "R:", "G");
    int grn = getColorValue(command, "G:", "B");
    int blu = getColorValue(command, "B:", ",");

    // Set the color of the entire Neopixel ring.
    uint16_t i;
    for (i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(red, grn, blu));
    }

    strip.show();

    return 1;
}

int getColorValue(String command, String first, String second) {

    int rgbValue;

    String val = command.substring(command.indexOf(first)+2, command.indexOf(second));
    val.trim();
    rgbValue = val.toInt();

    return rgbValue;
}

Solution

  • I ended up just modifying my code:

    int setColor(String command) {
        int commaIndex = command.indexOf(',');
        int secondCommaIndex = command.indexOf(',', commaIndex+1);
        int lastCommaIndex = command.lastIndexOf(',');
    
        String red = command.substring(0, commaIndex);
        String grn = command.substring(commaIndex+1, secondCommaIndex);
        String blu = command.substring(lastCommaIndex+1);
    
        // Set the color of the entire Neopixel ring.
        uint16_t i;
        for (i = 0; i < strip.numPixels(); i++) {
            strip.setPixelColor(i, strip.Color(red.toInt(), grn.toInt(), blu.toInt()));
        }
    
        strip.show();
    
        return 1;
    }
    

    I simply just do: 255,0,0 and it works a treat.