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