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