Wednesday, March 17, 2010

Random Number Generators (Tasks 34,35,36)

The following program writes a list of 100 random numbers on serial output
Code:
int value;
int count;
void setup(){
Serial.begin(9600);
delay(3000); //This delay allows for the serial monitor to be opened before the first number is generated
for (count = 0; count < 100; count++){
value = random(0,10);
Serial.println(value);
}
}
void loop(){
}

To give a more readable output we can alter the for loop:
for (count = 1; count < 101; count++){
value = random(0,11);
Serial.print(count);
Serial.print(". ");
Serial.println(value);
}

To generate averages from the above code it need to be altered slightly. On each cycle of the for loop it adds the randomized number to a total and then divides the total by 100. Code:
int value;
int count;
int total;

void setup(){
Serial.begin(9600);
randomSeed(analogRead(0));
delay(3000);
for (count = 1; count < 101; count++){
value = random(0,11);
total = total + value;
Serial.print(count);
Serial.print(". ");
Serial.println(value);
}
total = total / 100;
Serial.print("The average is ");
Serial.println(total);
}

void loop(){
}

No comments:

Post a Comment