Random pick one of the var in char type

Hi there, I am figuring out on how to randomly choose one of the char every time it runs. I have look thru the code below, but doesn't work for me plus I was told not to use string in Arduino.

char string[3][4] = { "abc", "def", "ghi"};

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
    randomSeed(analogRead(0));
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(string[random(0, 3)]);
  delay(1000);
}

Mine is just similar as this just that it does not work in my case, showing "too many initializers in char string"

Then show us your code. How are we supposed to guess what you did?

I mean, the code I showed is the same as what I trying to do,just that it does not work..

Try

char string[][4]

What is your environment? Your code compiles and runs as expected for me on a Uno with ide 1.8.13.

There are strings and there are Strings. Note the small and capital 's'. The strings are null terminated character arrays. The Strings are objects of the String class. Misuse of objects of the String class can cause memory problems. It is the use of Strings (capital S) that is discouraged.

In a sketch as small as this Strings are unlikely to cause any problem. If they do see my tutorial
Taming Arduino Strings

However what you have seems fine and runs for me to choose a whole string if that is what you are trying to do.

// https://forum.arduino.cc/t/random-pick-one-of-the-var-in-char-type/880577
char string[3][4] = { "abc", "def", "ghi"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  for (int i = 10; i > 0; i--) {
    delay(500);
    Serial.print(i); Serial.print(' ');
  }
  Serial.println("started ");
  randomSeed(analogRead(0));
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(string[random(0, 3)]);
  delay(1000);
}

Output

abc
ghi
def
abc
def
ghi
ghi
def

I am sorry for late reply, do you mind to further explain on the analog read part
? I cant seem to understand why it is there..

So you mean that analogRead()? Unless the random number generator is "seeded" at startup it will generate the same sequence of numbers every restart. See the randomSeed() reference.

1 Like

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