]> git.piffa.net Git - sketchbook_andrea/blob - multitasking/BlinkWithoutDelay_3_funzione/BlinkWithoutDelay_3_funzione.ino
multi cleanup
[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 = millis();   
55
56     // if the LED is off turn it on and vice-versa:
57     if (ledStateA == LOW)
58       ledStateA = HIGH;
59     else
60       ledStateA = LOW;
61     // set the LED with the ledState of the variable:
62     digitalWrite(ledA, ledStateA);
63   }
64
65 }
66
67 void lightLedB () {
68   long intervalB = 500;
69    static int ledStateB ;  // https://www.arduino.cc/en/Reference/Static
70   if (millis() > previousMillisB + intervalB) {
71     // save the last time you blinked the LED 
72     previousMillisB = millis();   
73
74     // if the LED is off turn it on and vice-versa:
75     if (ledStateB == LOW)
76       ledStateB = HIGH;
77     else
78       ledStateB = LOW;
79     // set the LED with the ledState of the variable:
80     digitalWrite(ledB, ledStateB);
81   }
82 }
83
84
85 /* Domande
86  1. Modificare le funzioni in modo che accettino come parametro
87  l'intervallo di lampeggio.
88  
89  */
90
91
92
93
94
95