Temp-4-4

From ArduinoInfo
Jump to navigation Jump to search
Head/Tails Example:

/* YourDuinoStarter Example: Sketch Template
 - WHAT IT DOES: Randomly lights LEDs labelled HEADS or TAILS
   - Keeps track of distribution
 - SEE the comments after "//" on each line below
 - CONNECTIONS:
   - HEADs LED Pin 11
   - TAILS LED Pin 10
 - V1.00 02/18/2015
   Questions: terry@yourduino.com */

/*-----( Import needed libraries )-----*/
// None Yet

/*-----( Declare Constants and Pin Numbers )-----*/
#define HEADS_LED_PIN  11
#define TAILS_LED_PIN  10

#define  PAUSE 10  // Both blank time and display time (ms)
// NOTE: Make this about 2000 ms (2 sec) to see the LEDs change
//       Make this about 10 ms to quickly see the resulting
//       distribution displayed on the Serial Monitor

/*-----( Declare objects )-----*/
// None Yet
/*-----( Declare Variables )-----*/
int  howManyHeads;
int  howManyTails;

long  loopCounter;
long  randomNumber = 0L;


void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(115200);
  pinMode(HEADS_LED_PIN, OUTPUT);
  pinMode(TAILS_LED_PIN, OUTPUT);
  howManyHeads = 0;
  howManyTails = 0;
  loopCounter = 0;

  /*--(Reads Analog pin 0, which has noisy, changing values,
    seeds the random number generator )-- */
  randomSeed(analogRead(A0));
}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  randomNumber = generateRandomNumber();
  digitalWrite(HEADS_LED_PIN, LOW);      // Turn both LED's off
  digitalWrite(TAILS_LED_PIN, LOW);

  delay(PAUSE);          // LED OFF time (ms)

  if (randomNumber % 2 == 1)
  { // Treat odd numbers as a head
    digitalWrite(HEADS_LED_PIN, HIGH);
    howManyHeads++;
  }
  else
  {
    digitalWrite(TAILS_LED_PIN, HIGH);       // Even numbers are a tail
    howManyTails++;
  }

  loopCounter++;
  if (loopCounter % 100 == 0)
  { // See how things are every 100 flips
    Serial.print("After ");
    Serial.print(loopCounter);
    Serial.print(" coin flips, heads = ");
    Serial.print(howManyHeads);
    Serial.print(" and tails = ");
    Serial.println(howManyTails);
  }// END show results

  delay(PAUSE);       // LED ON time (ms)
}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/
long generateRandomNumber()
{
  return random(0, 1000000);        // Random numbers between 0 and one million
}


//*********( THE END )***********