]> git.piffa.net Git - sketchbook_andrea/blob - advanced_projects/state_machine/semaforo_rgb/semaforo_rgb.ino
3260dbb03c76c74d4d464f1428eed5b5b2b76e94
[sketchbook_andrea] / advanced_projects / state_machine / semaforo_rgb / semaforo_rgb.ino
1 /*
2    Semaforo RGB
3    
4 Version: singolo semaforo + millis + memoria giallo
5
6    Un singolo semaforo costruito col paradigma delle macchine a stato.
7    Viene utilizzato un oggetto della libreria common per gestire il LED.
8
9    Uno stimolo esterno rappresentato dalla pressione di un bottone
10    causa il passaggio di stato.
11
12    Implementata con millis() invece che con delay(),
13    sono stati aggiuntu due stati per meglio gestire lo stato yellow.
14
15    */
16
17 #include <common.h>
18 const byte input = 2; // PIN del bottone
19 int pausa = 3000;
20 long timer ;
21 enum states_available { // Stati della FMS
22     green,         // Statico
23     yellow,            // Statico
24     red            // Statico
25 };
26
27 states_available state  ;
28 boolean wait = 0;
29
30
31 void setup() {
32     pinMode(input, INPUT_PULLUP);
33     Serial.begin(9600);
34     timer = millis();
35 }
36
37 RGBLed led(11, 10, 9); //Istanziamo un oggetto led facente parte
38 // della classe RGBLed
39
40 void loop() {
41     switch (state) {
42
43     case green:
44         led.Green();
45         if (wait && (millis() - timer >= pausa * 2/3)) {
46             state = yellow;
47             timer = millis();
48         }
49
50         if (digitalRead(input) == LOW) {
51             wait = 1;
52         }
53         break;
54
55
56     case yellow :
57         led.Yellow();
58         if (millis() - timer >= pausa /3) {
59             state = red ;
60             wait = 0 ;
61             timer += pausa /3;
62         }
63         break;
64
65     case red :
66         led.Red();
67         if (millis() - timer >= pausa) {
68             state = green ;
69             timer += pausa ;
70         }
71         break;
72
73     default:    // In caso di default si fa giallo lampeggiante
74         led.Yellow();
75         delay(pausa/3);
76         led.Off();
77         delay(pausa/3);
78         break;
79
80     }
81
82     //Debug:
83     Serial.print(millis());
84     Serial.print(" \t Stato attuale ");
85     Serial.print(state);
86     Serial.print(" \t Wait: ");
87     Serial.println(wait);
88
89 }
90
91 /* Domande:
92  1. Introdurre un secondo semaforo che cambia stato quando viene attivato
93     lo stimolo.
94  2. L'uso di delay() puo' essere limitativo: come rimediare?
95 .
96 .
97 .
98 .
99 .
100 .
101 .
102 .
103 .
104 .
105   Soluzioni
106 2. Si potrebbe utilizzare un interrupt per gli stimoli oppure millis()
107    per gestire le pause.
108  */