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