]> git.piffa.net Git - sketchbook_andrea/blob - programming/loops/loop_match_2_while_loop/loop_match_2_while_loop.ino
for loop
[sketchbook_andrea] / programming / loops / loop_match_2_while_loop / loop_match_2_while_loop.ino
1 /* Exercise 2, with a WHILE loop and a Break statement:
2 - http://arduino.cc/en/Reference/Break
3
4  Test a random number agains a value: 
5  a iteretive loop perform 255 runs to see if a random number in range 0-255
6  is equal to the target value set to 200.
7  
8  Light a led in case
9  Light the other LED if a run of 255 test has gone
10  Log the results (if success) trough serialport
11  */
12
13 // Data structure
14
15 const byte GREEN   = 13  ; // LED for found value
16 const byte RED     = 12 ;  // LEAD for restart
17
18 const int TARGET   = 200 ;
19 long randomNumber = 0L;
20
21 // Staff
22 const int WAIT = 1000 ;
23 const int REST = 10 ;
24 byte count = 0 ;
25 const byte MAXRUN = 10 ;
26 byte totalRun = 0 ;
27
28 void setup() {
29   pinMode(RED,OUTPUT);     
30   pinMode(GREEN,OUTPUT); 
31   // Serial stuff
32   Serial.begin(9600);
33   Serial.println("Initializing random sequence, please wait for results.");
34   randomSeed(analogRead(0)); // Random initializer
35 }
36
37 void loop() {  // put your main code here, to run repeatedly: 
38   digitalWrite(GREEN, LOW);  
39   digitalWrite(RED, LOW); 
40   // Serial.println(count);
41
42   while (count < 255) {
43     randomNumber = random(0,255); //Randoom value generated
44     Serial.print("|");
45     count++ ;  
46     delay(REST);
47     if (randomNumber == TARGET) {  // When we catch the value
48       Serial.println();
49       Serial.print("--> Match found! Counter was at: "); // serial message
50       Serial.println(count);
51       digitalWrite(GREEN, HIGH);
52       delay(WAIT);
53       count++ ;
54       break; // Interrompe il ciclo
55     }
56   }
57
58   Serial.println();
59   Serial.println("Counter resetted.");   // serial staff
60   count = 0;
61   digitalWrite(RED, HIGH);
62   delay(WAIT);
63   count++ ;
64   totalRun++ ;
65   if (totalRun == MAXRUN) {
66     Serial.println("10 runs done, exit program.");
67     digitalWrite(RED, HIGH);
68     delay(WAIT);
69     exit(0);
70   }
71
72
73