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