]> git.piffa.net Git - sketchbook_andrea/blob - basic/buttons/button_state_4_state/button_state_4_state.ino
a6a4e05e504198c8b1028fee93041107e7cbeab1
[sketchbook_andrea] / basic / buttons / button_state_4_state / button_state_4_state.ino
1 /*
2    Stato di un bottone
3  
4  Legge lo stato di un input
5  
6  */
7 int led = 13;              // Definizione delle variabili
8 int buttonPin = 2;              
9                            // Dichiarazione di variabili
10 int statoAttuale;          // Variabile per leggere lo stato del bottone
11 int ultimoStato;           // Variabile per registrare l'ultimo stato del bottone
12 int ledStatus;             // varabile per mantenere lo stato del led
13
14 void setup() {
15   pinMode(buttonPin, INPUT);    
16   pinMode(led, OUTPUT);    
17   Serial.begin(9600);                 // Attiva la comunicazione seriale a 9600bps
18   ultimoStato = digitalRead(buttonPin);   // Prima lettura del bottone
19   ledStatus = 0;                          // Il LED viene inpostato come spento                        
20 }
21
22 void loop(){
23   statoAttuale = digitalRead(buttonPin);      // Legge lo stato del bottone e lo resistra in val
24   delay(20);                                  // riduce l'effetto bounce
25   if (statoAttuale != ultimoStato) {          // lo stato del bottone e' cambiato
26     if (statoAttuale == HIGH) {               // il bottone e' stato premuto
27       Serial.println("Button premuto");
28      
29       ledStatus = !ledStatus ;          // Inverte lo stato del LED 
30       // ledStatus = 1 - ledStatus ;    // Forma analoga
31       
32       Serial.print("Stato del LED: ");  // DEBUG
33       Serial.println(ledStatus) ;
34     } 
35   }
36
37   ultimoStato = statoAttuale;        // Aggiorna lo stato finale al valore attuale
38   digitalWrite(led, ledStatus);      // setta il led allo stato richiesto
39
40 }
41
42
43