]> git.piffa.net Git - sketchbook_andrea/blob - multitasking/BlinkWithoutDelay_3_funzione/BlinkWithoutDelay_3_funzione.ino
State machine e blinks con millis()
[sketchbook_andrea] / multitasking / BlinkWithoutDelay_3_funzione / BlinkWithoutDelay_3_funzione.ino
1 /* Blink without Delay
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  */
12
13 /////////////
14 // First LED
15 const int ledA =  13;      // the number of the LED pin
16 // Variables will change:
17 int ledStateA = LOW;             // ledState used to set the LED
18 long previousMillisA = 0;        // will store last time LED was updated
19 // the follow variables is a long because the time, measured in miliseconds,
20 // will quickly become a bigger number than can be stored in an int.
21 long intervalA = 1000;           // interval at which to blink (milliseconds)
22 void lightLedA () ;
23
24 //////////////
25 //  Second LED
26 // Now with less global variables thanks to static (see function body)
27 const int ledB = 12; //Secondo LED
28            // ledState used to set the LED
29 long previousMillisB = 0;        // will store last time LED was updated
30            // interval at which to blink (milliseconds)
31 void lightLedB () ;
32
33
34 void setup() {
35   // set the digital pin as output:
36   pinMode(ledA, OUTPUT);      
37   pinMode(ledB, OUTPUT);  
38 }
39
40 void loop()
41 {
42   lightLedA();
43   lightLedB();
44 }
45
46
47 // Funzioni:
48
49 void lightLedA () {
50   if (millis() > previousMillisA + intervalA) {
51     // save the last time you blinked the LED 
52     previousMillisA = millis();   
53
54     // if the LED is off turn it on and vice-versa:
55     if (ledStateA == LOW)
56       ledStateA = HIGH;
57     else
58       ledStateA = LOW;
59     // set the LED with the ledState of the variable:
60     digitalWrite(ledA, ledStateA);
61   }
62
63 }
64
65 void lightLedB () {
66   long intervalB = 500;
67    static int ledStateB ;  // https://www.arduino.cc/en/Reference/Static
68   if (millis() > previousMillisB + intervalB) {
69     // save the last time you blinked the LED 
70     previousMillisB = millis();   
71
72     // if the LED is off turn it on and vice-versa:
73     if (ledStateB == LOW)
74       ledStateB = HIGH;
75     else
76       ledStateB = LOW;
77     // set the LED with the ledState of the variable:
78     digitalWrite(ledB, ledStateB);
79   }
80 }
81
82
83 /* Domande
84  1. Modificare le funzioni in modo che accettino come parametro
85  l'intervallo di lampeggio.
86  
87  */
88
89
90
91
92
93