]> git.piffa.net Git - sketchbook_andrea/blob - multitasking/BlinkWithoutDelay_3_funzione/BlinkWithoutDelay_3_funzione.ino
db0ed89e2c2ba043b3e395a795bc836cc52e742a
[sketchbook_andrea] / multitasking / BlinkWithoutDelay_3_funzione / BlinkWithoutDelay_3_funzione.ino
1 /* Blink without Delay: Refactoring
2  
3  Blink con funzione
4  
5  Soluzione: Provare a isolare il codice per accendere ogni singolo led in una funzione:
6  
7     - Quali variabili determinano il comportamento del LED?
8     - Come cambiano durante il corso dello script?
9     - Sono globali o locali? 
10
11 Variabili: http://www.maffucci.it/2011/12/15/appunti-di-programmazione-su-arduino-variabili/ 
12
13  */
14
15 /////////////
16 // First LED
17 const int ledA =  13;       // the number of the LED pin
18 // Variables will change:
19 int ledStateA = LOW;        // ledState used to set the LED
20 long previousMillisA = 0;   // will store last time LED was updated
21 // the follow variables is a long because the time, measured in miliseconds,
22 // will quickly become a bigger number than can be stored in an int.
23 long intervalA = 1000;      // interval at which to blink (milliseconds)
24 void lightLedA () ;
25
26 //////////////
27 //  Second LED
28 // Now with less global variables thanks to static (see function body)
29 const int ledB = 12; //Secondo LED
30                      // ledState used to set the LED
31 long previousMillisB = 0;    // will store last time LED was updated
32                              // interval at which to blink (milliseconds)
33 void lightLedB () ;
34
35
36 void setup() {
37   // set the digital pin as output:
38   pinMode(ledA, OUTPUT);      
39   pinMode(ledB, OUTPUT);  
40 }
41
42 void loop()
43 {
44   lightLedA();
45   lightLedB();
46 }
47
48
49 // Funzioni:
50
51 void lightLedA () {
52   if (millis() - previousMillisA >=  intervalA) {
53     // save the last time you blinked the LED 
54     previousMillisA += intervalA;
55
56     // if the LED is off turn it on and vice-versa:
57       ledStateA = !ledStateA ;
58     // set the LED with the ledState of the variable:
59     digitalWrite(ledA, ledStateA);
60   }
61
62 }
63
64 void lightLedB () {
65   long intervalB = 500;
66    static int ledStateB ;  // https://www.arduino.cc/en/Reference/Static
67   if (millis() - previousMillisB >= intervalB) {
68     // save the last time you blinked the LED 
69     previousMillisB += intervalB ;
70
71     // if the LED is off turn it on and vice-versa:
72       ledStateB = !ledStateB;
73     // set the LED with the ledState of the variable:
74     digitalWrite(ledB, ledStateB);
75   }
76 }
77
78
79 /* Domande
80  1. Modificare le funzioni in modo che accettino come parametro
81  l'intervallo di lampeggio.
82  
83  */
84
85
86
87
88
89