Temp 5 5 BOOK
Jump to navigation
Jump to search
_5_5_FindRandomTargetBook
/* Listing 5-5. Random Number Match */ // define the pins to be used. #define MAX 5000L #define MIN 0L #define TARGETVALUE 2500L #define MAXRECYCLES 5 #define FOUNDITIOPIN 10 // Use the green LED #define RECYCLEIOPIN 11 // Use the red LED #define PAUSE 1000 int foundIt = FOUNDITIOPIN; int recycle = RECYCLEIOPIN; long targetValue = TARGETVALUE; long randomNumber; int recycleCounter = 0; int counter = 0; void setup() { Serial.begin(9600); pinMode(foundIt, OUTPUT); pinMode(recycle, OUTPUT); randomSeed(analogRead(A0)); // This seeds the random number generator } void loop() { while (counter != -1) { // Check for negative values randomNumber = generateRandomNumber(); if (randomNumber == TARGETVALUE) { Serial.print("Counter = "); Serial.print(counter, DEC); Serial.print(" recycleCounter = "); Serial.println(recycleCounter, DEC); digitalWrite(foundIt, HIGH); delay(PAUSE); digitalWrite(foundIt, LOW); } counter++; if (counter < 0) { // We've overflowed an int counter = 0; recycleCounter++; Serial.print("recycleCounter = "); Serial.println(recycleCounter, DEC); digitalWrite(recycle, HIGH); delay(PAUSE); digitalWrite(recycle, LOW); } if (recycleCounter == MAXRECYCLES) { FakeAnEnd(); // End program } } }//Loop long generateRandomNumber() { return random(MIN, MAX); // Generate random numbers 0 and 5000 } void FakeAnEnd() { // Fake the end of the program while (true) { ; } }