]> git.piffa.net Git - arduino/blob - books/beginning_c_code/Chapter05/Listing5_1/Listing5_1.ino
gio
[arduino] / books / beginning_c_code / Chapter05 / Listing5_1 / Listing5_1.ino
1 // define the pins to be used.
2 #define MAX 5000L
3 #define MIN 0L
4 #define TARGETVALUE 2500L
5
6 #define MAXRECYCLES 5
7 #define FOUNDITIOPIN  13
8 #define RECYCLEIOPIN  12
9 #define PAUSE 1000
10
11
12 int foundIt = FOUNDITIOPIN;
13 int recycle = RECYCLEIOPIN;
14 long targetValue = TARGETVALUE;
15 long randomNumber;
16 int recycleCounter = 0;
17 int counter = 0;
18
19 // the setup routine runs once when you press reset:
20 void setup() {                
21   // initialize each of the digital pins as an output.
22   Serial.begin(9600);
23   pinMode(foundIt, OUTPUT);     
24   pinMode(recycle, OUTPUT);
25   randomSeed(analogRead(0)); // This seeds the random number generator
26
27 }
28
29 // the loop routine runs over and over again forever:
30 void loop() {
31
32   while (counter != -1) {      // Check for negative values
33     randomNumber = generateRandomNumber();
34     if (randomNumber == TARGETVALUE) {
35       Serial.print("Counter = ");
36       Serial.print(counter, DEC);
37       Serial.print("  recycleCounter = ");
38       Serial.println(recycleCounter, DEC);
39       digitalWrite(foundIt, HIGH);
40       delay(PAUSE);
41       digitalWrite(foundIt, LOW);
42     }
43     counter++;
44     if (counter < 0) {        // We've overflowed an int
45       counter = 0;
46       recycleCounter++;
47       Serial.print("recycleCounter = ");
48       Serial.println(recycleCounter, DEC);
49       digitalWrite(recycle, HIGH);
50       delay(PAUSE);
51       digitalWrite(recycle, LOW);
52     }
53
54     if (recycleCounter > MAXRECYCLES)
55       exit(0);                    // End program
56   }
57 }
58
59 long generateRandomNumber()
60 {
61   return random(MIN, MAX);     // Generate random numbers between 0 and one million
62 }
63 \r