]> git.piffa.net Git - arduino/blob - books/beginning_c_code/Chapter04/Listing4_2/Listing4_2.ino
first commit
[arduino] / books / beginning_c_code / Chapter04 / Listing4_2 / Listing4_2.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  
6    Dr. Purdum, July 12, 2012
7  */
8  
9 // define the pins to be used.
10 // give it a name:
11
12 #define HEADIOPIN 13    // Which I/O pins are we using?
13 #define TAILIOPIN 12
14
15 #define PAUSE 3000      // How long to delay?
16 #define REST 2000
17
18 int head = HEADIOPIN;
19 int tail = TAILIOPIN;
20 long randomNumber = 0L;
21
22 // the setup routine runs once when you press reset:
23 void setup() {                
24   // initialize each of the digital pins as an output.
25   pinMode(head, OUTPUT);     
26   pinMode(tail, OUTPUT);
27   randomSeed(analogRead(0)); // This seeds the random number generator
28 }
29
30 // the loop routine runs over and over again forever:
31 void loop() {
32
33   randomNumber = generateRandomNumber();
34   digitalWrite(head, LOW);      // Turn both LED's off
35   digitalWrite(tail, LOW);
36   delay(PAUSE - REST);          // Let them see both are off for a time slice
37   if (randomNumber % 2 == 1) {  // Treat odd numbers as a head
38     digitalWrite(head, HIGH);
39   } else {
40     digitalWrite(tail, HIGH);  // Even numbers are a tail
41   }
42   delay(PAUSE);                  // Pause for 3 seconds
43 }
44
45 long generateRandomNumber()
46 {
47   return random(0, 1000000);            // Generate random numbers between 0 and one million
48 }
49 \r