Grabbing the Next Item in Array of Strings

Yo. I'm trying to grab the next string in an array of strings on each loop. If I reach the end, start back at the beginning.

String modes[] = {"calendar", "weather"};
String mode = modes[0];

void loop() {
  int modeIndex = indexOf(mode, modes);
  if (modeIndex == sizeof(modes)) {
    mode = modes[0];
  } else {
    mode = modes[modeIndex + 1];
  }
  Serial.println("Fetching " + String(mode));
}

int indexOf(String item, String arr[]) {
  for (int i = 0; i < sizeof(arr); i++) {
    if (arr[i] == item) {
      return i;      
    }
  }
  return -1;
}

The first two times through, it works ("fetching calendar", "fetching weather"). Then, the third loop, I get "fetching false". What am I missing?

What is printed with the following

Serial.print(F("sizeof(modes) = ");
Serial.println(sizeof(modes));

How many elements are there in the modes array?

@xd1936
sizeof returns the total size of the variable. Not the number of indices of an array.
But you can get the size of one field of an array.
if you divide the total size by the size of the first field, you end up with the number of indices.

get rid of the Arduino Strings. You get cleaner and shorter code.


const char *modeTxt[] = {"calendar", "weather"};
size_t mode = 0; // current mode

void setup()
{
  Serial.begin(115200);
}

void loop() {
  //Serial.println("Fetching " + String(modeTxt[mode]));
  Serial.print(F("Fetching "));
  Serial.println(modeTxt[mode]);
  modeNext();
  delay(500); // dirty delay to slow down 
}

// increase mode, switch to next mode or wrap around on end
void modeNext()
{
  mode++;
  if (mode >= sizeof(modeTxt)/sizeof(modeTxt[0])) mode = 0;
}
1 Like

Thank you both for your guidance! I'm up and running now :slight_smile:

consider

const char *list [] = {
    "calendar",
    "news",
    "sports",
    "spiritual",
    "weather",
    0
};

// -----------------------------------------------------------------------------
void loop ()
{
    if (! Serial.available ())  
        return;

    char buf [80];
    int  n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
    buf [n] = '\0';

    for (const char **s = list; 0 != *s; s++)  {
        if (! strncmp (*s, buf, strlen (buf)))
            Serial.println (*s);
    }
}

// -----------------------------------------------------------------------------
void
setup (void)
{
    Serial.begin (115200);

    for (const char **s = list; 0 != *s; s++)
        Serial.println (*s);
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.