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.
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
15 long ultimoCambio = 0; // Momento in cui e' stato attivato il PIN input
16 long debounceDelay = 30; // Tempo di debounce
19 pinMode(buttonPin, INPUT); // Set the switch pin as input
21 Serial.begin(9600); // Set up serial communication at 9600bps
22 ultimoStato = digitalRead(buttonPin); // read the initial state
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
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");
37 ledStatus = !ledStatus ; // Inverte lo stato del LED
38 Serial.print("Stato del LED: "); // DEBUG
39 Serial.println(ledStatus) ;
43 ultimoStato = lettura; // save the new state in our variable
44 digitalWrite(led, ledStatus); // setta il led allo stato richiesto