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"
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);
}
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.