]> git.piffa.net Git - sketchbook_andrea/blob - programming/loops/loop_3_multi_led_random/loop_3_multi_led_random.ino
Loop e data type strutturati
[sketchbook_andrea] / programming / loops / loop_3_multi_led_random / loop_3_multi_led_random.ino
1 /*
2   Random Rainbow
3   
4   Generazione di un numero casuale per modificare il flusso del programma.
5   
6  
7
8  
9  The circuit:
10  * LEDs from pins 2 through 9 to ground
11  
12  Schemi:
13  - http://lab.piffa.net/schemi/8_led_single_res_bb.png
14  - http://lab.piffa.net/schemi/8_led_single_res_schem.png
15  
16  http://www.arduino.cc/en/Tutorial/ForLoop
17  */
18
19 byte ledPins[8] = {  // Domanda: cosa succede se uso int?
20   2,3,4,5,6,7,8,9
21   }; //Array
22 int timer = 100;           // Pausa per far brillare i LED
23 int randNumber ;
24
25 void setup() {
26   Serial.begin(9600);
27   // use a for loop to initialize each pin as an output:
28   for (int thisPin = 0; thisPin < sizeof(ledPins); thisPin++)  {
29     pinMode(ledPins[thisPin], OUTPUT);
30     Serial.print("Inizializzato pin n. ");
31     Serial.println(  thisPin);
32   }
33
34   Serial.print("Dimesione array: ");
35   Serial.println(sizeof(ledPins));
36   
37   randomSeed(analogRead(0));  // Rilevazione di un valore esterno
38  // per scegliere il primo elemento del pseudorandom generators
39 }
40
41 void loop() {
42   // print a random number from 0 to 7
43   randNumber = random(8);
44   // turn the pin on:
45   Serial.print("Accensione pin  n. ");
46   Serial.println(randNumber);
47   digitalWrite(ledPins[randNumber], HIGH);  
48   delay(timer);                  
49   // turn the pin off:
50   digitalWrite(ledPins[randNumber], LOW);    
51
52   if (randNumber == 0) {
53     rainbow() ;
54   }
55 }
56
57 ////////////////
58 // Funzioni
59
60 void rainbow() {
61   // Esegue un pattern con i led
62   
63   Serial.println(">>> Rainbow! <<<");
64     // loop from the lowest pin to the highest:
65   for (int thisPin = 0; thisPin < sizeof(ledPins); thisPin++) {
66     // turn the pin on:
67     digitalWrite(ledPins[thisPin], HIGH);  
68     delay(timer / 2);                  
69     // turn the pin off:
70     digitalWrite(ledPins[thisPin], LOW);    
71   }
72
73   // loop from the highest pin to the lowest:
74   for (int thisPin = sizeof(ledPins) -1 ; thisPin > 0; thisPin--) {
75     // ><<turn the pin on:
76     digitalWrite(ledPins[thisPin], HIGH);
77     delay(timer / 3);
78     // turn the pin off:
79     digitalWrite(ledPins[thisPin], LOW);
80   }
81 }
82
83
84
85
86