Rickstar
Rickstar

Reputation: 6199

How to add to an array - Arduino

I am trying to start off with a empty array and then generate a random number patten using the following code but I seem to not be able to get it to work.

 int sequence = {};

 random(1, 4);

 for (int i=0; i <= 7; i++){
 sequence[i] = random(1, 4);
 } 

Upvotes: 3

Views: 31650

Answers (3)

Paul Isaac
Paul Isaac

Reputation: 84

This is how I would do it, it compiled just fine on my arduino IDE. I don't think it is necessary to seed the rand function, unless your application calls for a truly random number (not repeatable).

https://www.arduino.cc/en/reference/random should help you out

void loop() {
 int sequence[8]; // this is an array

 for (int i=0; i <= 7; i++){
 // use modulo to get remainder, add 1 to make it a range of 1-4
 sequence[i] = rand() % 4 + 1;
 }
}

Upvotes: 2

Anycorn
Anycorn

Reputation: 51555

That's not an array.
This is an array, int sequence[7];

Upvotes: 1

borges
borges

Reputation: 3687

Arduino is based on C++.

int sequence[8];

// You must initialize the pseudo-random number generator
// You can get a "random seed" using analogRead(0) if this
// pin isn't been used and unplugged.
randomSeed(analogRead(0));

for (int i=0; i <= 7; i++){
    sequence[i] = random(1, 4);

Upvotes: 4

Related Questions