]> git.piffa.net Git - arduino/blob - books/beginning_c_code/Chapter04/Exercise4_4/Exercise4_4.ino
first commit
[arduino] / books / beginning_c_code / Chapter04 / Exercise4_4 / Exercise4_4.ino
1 /*
2   Heads or Tails
3   Turns on an LED which represents head or tails. The LED 
4   remains on for about 3 seconds and the cycle repeats.
5    Dr. Purdum, July 12, 2012
6  */
7  
8 // define the pins to be used.
9 #define SENDMESSAGEAFTERTHISMANYTOSSES 100
10 #define TESTSTORUN 50000
11 #define HEADIOPIN  13
12 #define TAILIOPIN  12
13
14 int head = HEADIOPIN;
15 int tail = TAILIOPIN;
16 long randomNumber = 0L;
17 long headCount = 0L;
18 long tailCount = 0L;
19
20 // the setup routine runs once when you press reset:
21 void setup() {                
22   // initialize each of the digital pins as an output.
23   Serial.begin(9600);
24   pinMode(head, OUTPUT);     
25   pinMode(tail, OUTPUT);
26   randomSeed(analogRead(0)); // This seeds the random number generator
27 }
28
29 // the loop routine runs over and over again forever:
30 void loop() {
31   randomNumber = generateRandomNumber();
32   digitalWrite(head, LOW);      // Turn both LEDs off
33   digitalWrite(tail, LOW);
34
35   if (randomNumber % 2 == 1) {  // Treat odd numbers as a head
36     digitalWrite(head, HIGH);
37     headCount++;
38   } else {
39      digitalWrite(tail, HIGH);  // Even numbers are a tail
40      tailCount++;
41   }
42  
43   if ( (headCount + tailCount) % SENDMESSAGEAFTERTHISMANYTOSSES == 0) {
44     Serial.print("Heads = ");
45     Serial.print(headCount);
46     Serial.print("   tails = ");
47     Serial.println(tailCount);
48   }
49   if (headCount + tailCount > TESTSTORUN) {
50     Serial.flush();
51     exit(0);
52    }
53 }
54
55 long generateRandomNumber()
56 {
57   return random(0, 1000000);     // Generate random numbers between 0 and one million
58 }
59 \r