]> git.piffa.net Git - sketchbook_andrea/blob - basic/buttons/debounce/debounce.ino
Buttons and serial
[sketchbook_andrea] / basic / buttons / debounce / debounce.ino
1 /*
2    Stato di un bottone
3  
4  Modifica lo stato di un led in base all'input di un bottone.
5  Viene usato un ciclo condizionale ramificato
6  e due variabili per confrontare il periodo di pressione del bottone.
7  
8  */
9 int led = 13;
10 int buttonPin = 2;              
11 int statoAttuale;                        // variable for reading the pin status
12 int ultimoStato;                // variable to hold the last button state
13 int ledStatus = 0;             // varabile per mantenere lo stato del led
14
15 long ultimoCambio = 0;  // Momento in cui e' stato attivato il PIN input
16 long debounceDelay = 30;    // Tempo di debounce
17
18 void setup() {
19   pinMode(buttonPin, INPUT);    // Set the switch pin as input
20   pinMode(led, OUTPUT);    
21   Serial.begin(9600);           // Set up serial communication at 9600bps
22   ultimoStato = digitalRead(buttonPin);   // read the initial state
23 }
24
25 void loop(){
26   int lettura = digitalRead(buttonPin);      // read input value and store it in var
27   if (lettura != ultimoStato) { // controlla se il bottone ha cambiato stato
28     ultimoCambio = millis() ;    // Registra il tempo attuale
29   }
30
31   if ((millis() - ultimoCambio) > debounceDelay) { // controllo che il periodo di tempo sia sufficente
32     if (lettura != statoAttuale) {        // Il bottone ha cambiato stato
33       statoAttuale = lettura;             // Evitiamo che la precedente condizione si ripeta ad oltranza
34       if (statoAttuale == HIGH) {                // check if the button is pressed
35         Serial.println("Button premuto");
36
37         ledStatus = !ledStatus ;    // Inverte lo stato del LED 
38         Serial.print("Stato del LED: ");  // DEBUG
39         Serial.println(ledStatus) ;
40       } 
41     }
42   }
43   ultimoStato = lettura;                 // save the new state in our variable
44   digitalWrite(led, ledStatus);      // setta il led allo stato richiesto
45
46 }
47
48
49
50
51
52