OK All I need is pretty much some simple help. I'll try and explain as best as I can.
I'm generating a random number using the random function, but I want that number to be put into an array, but with all the numbers below it descending to 1, for example, if the random number generator picks 4, the array will be { 1, 2, 3, 4 } I'm quite new to Arduino so I'd appreciate any help, I think it should be quite simple, thank you!
My sketch so far; (Electronic Die)
int time = 500; //500ms delay for the number
int buttonPin = 10; //button pin to display the dice
int count = 0;
int pinArray[] = {2, 3, 4, 5, 6, 7, 8, 9};
void setup() {
for (count=0;count<8;count++) {
pinMode(pinArray[count], OUTPUT);
}
}
void loop() {
int button = 0; // checks if button is pressed
button = digitalRead(buttonPin);
if(button == 1) { //checks if button is pressed
{
LED(); //call LED function
}
}
}
void LED() {
int num = random(1,9); //generate random number
int LEDon = num + 1;
digitalWrite(LEDon, HIGH); //sets the LED on
delay(time); //wait 500 ms
digitalWrite(LEDon, LOW); //sets the LED off
}
I'm generating a random number using the random function, but I want that number to be put into an array, but with all the numbers below it descending to 1, for example, if the random number generator picks 4, the array will be { 1, 2, 3, 4 }
A for loop, starting at 1, ending at the required upper limit, would do that. But, why?
If you know that every element in the array is i+1, where i is the element index, why do you need to have stored i+1 in position i?
I don't understand what you mean sorry I'm really new to this.
All I want to do is the numbers to be put into an array, if it picks 5, it puts { 1, 2, 3, 4, 5 } into an array, that's all I want to do.
int num = random(1,9); //generate random number
for (int i=1; i<=num; i++)
array[i-1] = i;
Since 'array[i-1]' is always equal to 'i' it makes little sense to put these values in an array. If you know the array index you can calculate the contents of that array element about as fast as you can fetch it from the array.
int randNum = random(1,9);
int dumb[9];
for(int i=0; i<9; i++)
{
if(i<randNum)
dumb[i] = i+1;
else
dumb[i] = 0;
}
But, again, why? The index to the array, whenever you get around to using it, is ALWAYS going to be 1 less than the value in the array at that position, so the array is useless.