/*
- Adafruit Arduino - Lesson 3. RGB LED
+ RGB Array
- RGB LED: mpostare i colori per un LED RGB
- common anode
+ RGB LED: impostare i colori per un LED RGB
+ common anode tramite array
Schema: http://lab.piffa.net/schemi/rgb.jpg
*/
{
analogWrite(pin[0], color[0]);
analogWrite(pin[1], color[1]);
- analogWrite(pin[2], color[1]);
+ analogWrite(pin[2], color[2]);
}
/* Domande:
/*
- Adafruit Arduino - Lesson 3. RGB LED
+ RGB struct LED
RGB LED: mpostare i colori per un LED RGB
- common anode
+ common anode utilizzando uno struct
Schema: http://lab.piffa.net/schemi/rgb.jpg
*/
*/
+/* Risposte:
+ * 1.
+struct ledRGB {
+ byte r;
+ byte g;
+ byte b;
+ byte blue;
+ byte green;
+ byte red;
+};
+
+ledRGB led {0,255,255,9,10,11};
+
+
+
+void setup()
+{
+ pinMode(led.blue, OUTPUT);
+ pinMode(led.green, OUTPUT);
+ pinMode(led.red, OUTPUT);
+}
+
+void loop()
+{
+ analogWrite(led.red,led.r );
+ analogWrite(led.green,led.g);
+ analogWrite(led.blue,led.b);
+}
+*/
/*
- Adafruit Arduino - Lesson 3. RGB LED
+ RGB Object
- RGB LED: mpostare i colori per un LED RGB
- common anode
+ Gestione di un LED RGB tramite programmazione a oggetti
Schema: http://lab.piffa.net/schemi/rgb.jpg
*/
class RGBLed {
- const byte redPin ;
- const byte greenPin ;
- const byte bluePin ;
+ // Classe rappresentativa di un LED RGB
+
+ byte redPin ;
+ byte greenPin ;
+ byte bluePin ;
byte redValue ;
byte greenValue ;
byte blueValue ;
pinMode(greenPin, OUTPUT);
}
- void Color (byte r, byte g, byte b) {
+ void Arrossa () {
+ // Metodo = funzione dell'oggetto
+ // Imposta il colore di un LED RGB a rosso
+
+ analogWrite(redPin, 0);
+ analogWrite(greenPin, 255);
+ analogWrite(bluePin, 255);
+ }
+
+ void SetColor (byte r, byte g, byte b) {
// Imposta il colore di un LED RGB
- byte redValue = r;
- byte greenValue = g;
- byte blueValue = b;
- analogWrite(redPin, redValue);
- analogWrite(greenPin, greenValue);
- analogWrite(bluePin, blueValue);
+ analogWrite(redPin, r);
+ analogWrite(greenPin, g);
+ analogWrite(bluePin, b);
}
};
// Instanziamo un LED
-RGBLed led(11, 10, 9);
+RGBLed led(11, 10, 9);
/* L'oggetto viene istanziato qui e non nella funzione di setup()
- * perche' altrimenti la sua esistenza sarebbe legata solo
+ * perche' altrimenti la sua esistenza sarebbe legata solo
* al contesto (scope) del setup(), non sarebbe disponibile nel loop()
*/
void setup() {
- // I PIN mode vengono settati dal constructor
- }
+ // I PIN mode vengono settati dal constructor
+}
+void loop() {
+ led.Arrossa();
+ delay(1000);
+ led.SetColor(255, 0, 255) ; // Mettiamo il LED in Green
+ delay(1000);
-void loop(){
-led.Color(0,255,255) ; // Mettiamo il LED in Rosso
- }
+}
--- /dev/null
+/*
+ Blink con state machine
+
+ Introduzione alle state machine
+
+ */
+int led = 13;
+int pausa = 1000;
+enum states_available { // Stati della FMS
+ turn_on, // Dinamico, transizione
+ on, // Statico
+ turn_off,
+ off
+};
+
+states_available state ;
+
+void setup() {
+ pinMode(led, OUTPUT);
+ Serial.begin(9600);
+ Serial.flush();
+}
+
+void loop() {
+switch (state) {
+ case turn_on :
+ digitalWrite(led, HIGH);
+ state = on ; // Setta il prossimo state
+ break;
+
+ case on:
+ delay(pausa);
+ state = turn_off ;
+ break;
+
+ case turn_off :
+ digitalWrite(led, LOW);
+ state = off ;
+ break;
+
+ case off :
+ delay(pausa);
+ state = turn_on ;
+ break;
+
+ default: // In caso di default si fa turn_off
+ digitalWrite(led, LOW);
+ state = off ;
+ break;
+
+}
+Serial.print(millis());
+Serial.print(" \t Stato attuale ");
+Serial.println(state);
+
+}
--- /dev/null
+/*
+ Semaforo RGB
+
+ Un singolo semaforo costruito col paradigma delle macchine a stato.
+ Viene utilizzato un oggetto della libreria common per gestire il LED.
+
+ */
+#include <common.h>
+int pausa = 3000;
+enum states_available { // Stati della FMS
+ turn_green, // Dinamico, transizione
+ green, // Statico
+ turn_red,
+ red
+};
+
+states_available state ;
+
+
+void setup() {
+ Serial.begin(9600);
+ Serial.flush();
+}
+
+RGBLed led(11, 10, 9); //Istanziamo un oggetto led facente parte
+ // della classe RGBLed
+
+void loop() {
+switch (state) {
+ case turn_green :
+ led.Green();
+ state = green ; // Setta il prossimo state
+ break;
+
+ case green:
+ delay(pausa * 2/3);
+ state = turn_red ;
+ break;
+
+ case turn_red :
+ led.Yellow();
+ delay(pausa/3);
+ led.Red();
+ delay(pausa);
+ state = red ;
+ break;
+
+ case red :
+ delay(pausa);
+ state = turn_green ;
+ break;
+
+ default: // In caso di default si fa giallo
+ led.Yellow();
+ delay(pausa/3);
+ led.Off();
+ delay(pausa/3);
+ break;
+
+}
+Serial.print(millis());
+Serial.print(" \t Stato attuale ");
+Serial.println(state);
+
+}
+
+/* Domande:
+ 1. Come legare il passaggio di stato ad un evento esterno,
+ ad es. la pressione di un bottone?
+ */
--- /dev/null
+/*
+ Semaforo RGB
+
+ Un singolo semaforo costruito col paradigma delle macchine a stato.
+ Viene utilizzato un oggetto della libreria common per gestire il LED.
+
+ Uno stimolo esterno rappresentato dalla pressione di un bottone
+ causa il passaggio di stato.
+
+ */
+#include <common.h>
+const byte input = 2; // PIN del bottone
+int pausa = 3000;
+enum states_available { // Stati della FMS
+ turn_green, // Dinamico, transizione
+ green, // Statico
+ wait_button,
+ turn_red,
+ red
+};
+
+states_available state ;
+
+
+void setup() {
+ pinMode(input, INPUT_PULLUP);
+ Serial.begin(9600);
+ Serial.flush();
+}
+
+RGBLed led(11, 10, 9); //Istanziamo un oggetto led facente parte
+ // della classe RGBLed
+
+void loop() {
+switch (state) {
+ case turn_green :
+ led.Green();
+ state = green ; // Setta il prossimo state
+ break;
+
+ case green:
+ delay(pausa * 2/3);
+ state = wait_button ;
+ break;
+
+ case wait_button:
+ if (digitalRead(input) == LOW) {
+ state = turn_red ; // Il passaggio di stato avviene alla pressione di un bottone
+ delay(20);
+ };
+
+ break;
+
+ case turn_red :
+ led.Yellow();
+ delay(pausa/3);
+ led.Red();
+ delay(pausa);
+ state = red ;
+ break;
+
+ case red :
+ delay(pausa);
+ state = turn_green ;
+ break;
+
+ default: // In caso di default si fa giallo lampeggiante
+ led.Yellow();
+ delay(pausa/3);
+ led.Off();
+ delay(pausa/3);
+ break;
+
+}
+Serial.print(millis());
+Serial.print(" \t Stato attuale ");
+Serial.println(state);
+
+}
+
+/* Domande:
+ 1. Introdurre un secondo semaforo che cambia stato quando viene attivato
+ lo stimolo.
+ 2. L'uso di delay() puo' essere limitativo: come rimediare?
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+ Soluzioni
+2. Si potrebbe utilizzare un interrupt per gli stimoli oppure millis()
+ per gestire le pause.
+ */
--- /dev/null
+/*
+A traffic light for an intersection of a
+highway and a country road. Normally, the light
+should be green for the highway and red for the
+country road, but when traffic approaches on
+the country road, the highway gets a red light
+and the country road gets a green light.
+
+When a light turns red it transitions from green to
+red it goes through yellow, but a red light changing
+to green transitions directly to green.
+
+A pushbutton represents a car approaching on
+the country road.
+
+Implement the solution with a Finite State
+Machine or FSM.
+
+Following the excellent description at
+http://hacking.majenko.co.uk/finite-state-machine
+first break down the problem into states.
+
+Identify which states are Transitional (T) and
+which are Static (S). A Static state is one in
+which the FSM is waiting for stimulus, and is
+taking no actions. A Transitional State is a
+state which causes actions, but doesn't look
+for stimulus.
+
+A Transitional State runs once and immediately
+moves on to a Static State.
+
+State 0: highway = green, country = red; (T)
+State 1: wait for car on country road (S)
+State 2: highway = yellow, make note of current time (T)
+State 3: wait for yellow time to pass (S)
+State 4: highway = red, country = green, make note of current time (T)
+State 5: wait for highway red time to pass (S)
+State 6: country = yellow, make note of current time (T)
+state 7: wait for yellow time to pass (S) then go to 0
+*/
+
+// Use names for states so it's easier to
+// understand what the code is doing
+const int S_HIGHWAYGREEN = 0;
+const int S_WAITCARCOUNTRY = 1;
+const int S_HIGHWAYYELLOW = 2;
+const int S_WAITHIGHWAYYELLOW = 3;
+const int S_HIGHWAYRED = 4;
+const int S_WAITHIGHWAYRED = 5;
+const int S_COUNTRYYELLOW = 6;
+const int S_WAITCOUNTRYYELLOW = 7;
+
+// Pin numbers
+const int countrySensorPin = 2;
+
+const int highwayGreenLEDPin = 3;
+const int highwayYellowLEDPin = 4;
+const int highwayRedLEDPin = 5;
+
+const int countryGreenLEDPin = 6;
+const int countryYellowLEDPin = 7;
+const int countryRedLEDPin = 8;
+
+void setup()
+{
+ pinMode(highwayGreenLEDPin, OUTPUT);
+ pinMode(highwayYellowLEDPin, OUTPUT);
+ pinMode(highwayRedLEDPin, OUTPUT);
+ pinMode(countryGreenLEDPin, OUTPUT);
+ pinMode(countryYellowLEDPin, OUTPUT);
+ pinMode(countryRedLEDPin, OUTPUT);
+}
+
+void loop()
+{
+
+ // start off with the highway getting green
+ // The keyword "static" makes sure the variable
+ // isn't destroyed after each loop
+ static int state = S_HIGHWAYGREEN ;
+
+ // To store the current time for delays
+ static unsigned long ts;
+
+ switch (state)
+ {
+ case S_HIGHWAYGREEN:
+ // Highway gets green, country road red
+ digitalWrite( highwayGreenLEDPin, HIGH);
+ digitalWrite( highwayYellowLEDPin, LOW);
+ digitalWrite( highwayRedLEDPin, LOW);
+
+ digitalWrite( countryGreenLEDPin, LOW);
+ digitalWrite( countryYellowLEDPin, LOW);
+ digitalWrite( countryRedLEDPin, HIGH);
+
+ state = S_WAITCARCOUNTRY;
+
+ break;
+
+ case S_WAITCARCOUNTRY:
+
+ if ( digitalRead (countrySensorPin) == HIGH) {
+ state = S_HIGHWAYYELLOW;
+ }
+
+ break;
+
+ case S_HIGHWAYYELLOW:
+ digitalWrite( highwayGreenLEDPin, LOW);
+ digitalWrite( highwayYellowLEDPin, HIGH);
+ digitalWrite( highwayRedLEDPin, LOW);
+
+ digitalWrite( countryGreenLEDPin, LOW);
+ digitalWrite( countryYellowLEDPin, LOW);
+ digitalWrite( countryRedLEDPin, HIGH);
+
+ ts = millis(); // Remember the current time
+
+ state = S_WAITHIGHWAYYELLOW; // Move to the next state
+
+ break;
+
+ case S_WAITHIGHWAYYELLOW:
+ // If two seconds have passed, then move on to the next state.
+ if (millis() > ts + 2000)
+ {
+ state = S_HIGHWAYRED;
+ }
+
+ break;
+
+ case S_HIGHWAYRED:
+ // Highway red, country road green
+ digitalWrite( highwayGreenLEDPin, LOW);
+ digitalWrite( highwayYellowLEDPin, LOW);
+ digitalWrite( highwayRedLEDPin, HIGH);
+
+ digitalWrite( countryGreenLEDPin, HIGH);
+ digitalWrite( countryYellowLEDPin, LOW);
+ digitalWrite( countryRedLEDPin, LOW);
+
+ ts = millis(); // Remember the current time
+
+ state = S_WAITHIGHWAYRED;
+
+ break;
+
+ case S_WAITHIGHWAYRED:
+
+ // If five seconds have passed, then start
+ // transition to a red light for the country
+ // road
+ if (millis() > ts + 5000)
+ {
+ state = S_COUNTRYYELLOW;
+ }
+
+ break;
+
+ case S_COUNTRYYELLOW:
+ digitalWrite( highwayGreenLEDPin, LOW);
+ digitalWrite( highwayYellowLEDPin, LOW);
+ digitalWrite( highwayRedLEDPin, HIGH);
+
+ digitalWrite( countryGreenLEDPin, LOW);
+ digitalWrite( countryYellowLEDPin, HIGH);
+ digitalWrite( countryRedLEDPin, LOW);
+
+ ts = millis(); // Remember the current time
+
+ state = S_WAITCOUNTRYYELLOW;
+
+ break;
+
+ case S_WAITCOUNTRYYELLOW:
+
+ // If two seconds have passed, then go
+ // back to the beginning with the highway
+ // getting the green light
+ if (millis() > ts + 2000)
+ {
+ state = S_HIGHWAYGREEN;
+ }
+
+ break;
+
+ } // end of switch
+
+ // other things could go on here, and they would not affect the timing
+ // of the traffic light
+
+} // end of loop
void setup() {
// turn on LED to signal the start of the calibration period:
pinMode(13, OUTPUT);
+ pinMode(ledPin, OUTPUT);
digitalWrite(13, HIGH);
// calibrate during the first five seconds
--- /dev/null
+/*
+ Blink v7: diodi
+
+ Accensione e spegnimanto di 2 LED invertendo il verso di percorrenza
+ della corrente elettrica con un solo PIN di OUTPUT.
+
+
+Schema: http://www.pighixxx.com/test/portfolio-items/light-two-leds/?portfolioID=610
+
+ Ricordarsi di usare una resistenza da ~320ohms per i LED.
+ Resistenza = (Voltaggio_Arduino - Forward_voltage_LED) / (ampere utilizzati)
+ R = (5v-1.8v) / 0.010a
+ R =320ohms
+
+ This example code is in the public domain.
+ */
+
+
+int led = 2; // Pin per i LED
+int pause = 200; // Variabile richiambile nel corso dell'esecuzione
+
+
+void setup() {
+ pinMode(led, OUTPUT); // Abilitaiamo entrambi i LED, questo comporta
+ // collegarli dalla resistenza interna!
+}
+
+
+void loop() {
+ digitalWrite(led, HIGH); // turn the 1st LED on (HIGH is the voltage level)
+ delay(pause); // wait for a second
+
+ digitalWrite(led, LOW); // turn the 2nd LED on by making the voltage LOW
+ delay(pause); // wait for a second
+}
+
+
+/* Domande
+ *
+ 1. Quanti stati sono disponibili per i LED ?
+ 2. Sarebbe possibile spegnere conemporaneamente entrambi i LED?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Risposte:
+ 1. Be' un digital out puo' essere a 0 oppure 5v.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 2. Si: trasformando il PIN da OUTPUT a INPUT questo diventerebbe
+ ad alta impendenza impedendo anche il DRAIN di corrente.
+ Da un punto di vista fisico si potrebbe lavorare sul tempo di attivazione
+ del LED: facendo oscillare il pin a una frequenza superiore al periodo
+ necessario di attivazione del LED si potrebbe impedire l'accensione
+ anche come UOTPUT.
+
+*/
}
+/* Domande
+ *
+ 1. Quanti stati sono disponibili per i LED ?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Risposte:
+ 1. Quattro combinazione tra cui 3 stati differenti.
+ */
2. Modificare il programma per far brillare il led cinque volte al secondo
quando il bottone e' premuto.
3. Si potrebbe usare un ciclo iterativo while invece che
- un ciclo condizonale if? Che differenza c'e' tra il ciclo while e for?
+ un ciclo condizonale if? Che differenza c'e' tra il ciclo while, if e for?
4. Domanda: cosa succede se il jumper input non e' collegato ne al +5 ne al ground?
*/
void loop(){
- statoAttuale = digitalRead(switchPin); // Legge lo stato del bottone e lo resistra in val
+ statoAttuale = digitalRead(switchPin); // Legge lo stato del bottone e
+ // lo resistra nella variabile
delay(20); // riduce l'effetto bounce
if (statoAttuale != ultimoStato) {
// verifica due condizioni che devono realizzarsi contemporaneamente
delay(20); // riduce l'effetto bounce
if (statoAttuale != ultimoStato && statoAttuale == HIGH) { // due condizione contemporanee
// lo stato del bottone e' camabiato AND lo stato attuale e' HIGH
- digitalWrite(led, !(digitalRead(led))); // Il processore setta lo stato di un led
- // impostando il relativo PIN: possiamo leggere il relativo registro allo stesso modo di un bottone.
+ digitalWrite(led, !(digitalRead(led)));
+ // Il processore setta lo stato di un led
+ // impostando il relativo PIN: possiamo leggere il relativo registro
+ // allo stesso modo di un bottone.
}
- ultimoStato = statoAttuale; // Aggiorna lo stato finale al valore attuale
+ ultimoStato = statoAttuale; // Aggiorna lo stato finale al valore attuale
}
}
void loop(){
- statoAttuale = digitalRead(buttonPin); // Legge lo stato del bottone e lo registra in val
+ statoAttuale = digitalRead(buttonPin); // Legge lo stato del bottone e
+ // lo registra nella variabile
delay(20); // riduce l'effetto bounce
if (statoAttuale != ultimoStato) { // lo stato del bottone e' cambiato
if (statoAttuale == HIGH) { // il bottone e' stato premuto
1. Per accendere o spegnere un LED Arduino imposta il valore del registro corrispondente
al PIN: se questo e' 0 il circuito e' aperto mentre se e' 1 il circuito e' chiuso.
- Allo stesso modo con DigitalRead() e' possibile leggere lo stato di quel regustro
+ Allo stesso modo con DigitalRead() e' possibile leggere lo stato di quel registro
e conoscere se il LED e' acceso o spento.
+ - https://www.arduino.cc/en/Reference/PortManipulation
+ - http://www.instructables.com/id/Microcontroller-Register-Manipulation/
*/
--- /dev/null
+/* Common
+ *
+ * Oggetti di uso comune
+ */
+
+#include "Arduino.h"
+#include "common.h"
+
+
+//////////////////////
+// RGB LED
+// Common anode
+
+RGBLed::RGBLed(byte pinR, byte pinG, byte pinB) {
+ redPin = pinR ;
+ greenPin = pinG ;
+ bluePin = pinB ;
+
+ // Equvalente del Setup() per inizializzare i PIN
+ pinMode(redPin, OUTPUT);
+ pinMode(greenPin, OUTPUT);
+ pinMode(greenPin, OUTPUT);
+};
+
+void RGBLed::Red () {
+// Accende il LED di rosso
+ analogWrite(redPin, 0);
+ analogWrite(greenPin, 255);
+ analogWrite(bluePin, 255);
+ };
+
+void RGBLed::Green () {
+// Accende il LED di verde
+ analogWrite(redPin, 255);
+ analogWrite(greenPin, 0);
+ analogWrite(bluePin, 255);
+ };
+
+void RGBLed::Blue () {
+// Accende il LED di blu
+ analogWrite(redPin, 255);
+ analogWrite(greenPin, 255);
+ analogWrite(bluePin, 0);
+ };
+
+void RGBLed::Magenta () {
+// Accende il LED di magenta
+ analogWrite(redPin, 0);
+ analogWrite(greenPin, 255);
+ analogWrite(bluePin, 0);
+ };
+
+void RGBLed::Cyano () {
+// Accende il LED di Cyano
+ analogWrite(redPin, 255);
+ analogWrite(greenPin, 0);
+ analogWrite(bluePin, 0);
+ };
+
+void RGBLed::Yellow () {
+// Accende il LED di giallo
+ analogWrite(redPin, 0);
+ analogWrite(greenPin, 0);
+ analogWrite(bluePin, 255);
+ };
+
+void RGBLed::White () {
+// Accende il LED
+ analogWrite(redPin, 0);
+ analogWrite(greenPin, 0);
+ analogWrite(bluePin, 0);
+ };
+
+void RGBLed::Off () {
+// Spegne il LED
+ analogWrite(redPin, 255);
+ analogWrite(greenPin, 255);
+ analogWrite(bluePin, 255);
+ };
+
+void RGBLed::SetColor (byte r, byte g, byte b) {
+ // Imposta il colore di un LED RGB
+
+ analogWrite(redPin, r);
+ analogWrite(greenPin, g);
+ analogWrite(bluePin, b);
+ };
+
+
+//////////////////
+// Funzioni
+
+void brilla(byte pin) {
+ // Accende e spegne il LED senza un argomento
+ // per impostare la velocita'.
+ const int velocita = 500;
+
+pinMode(pin, OUTPUT);
+ // sequenze di istruzione: accendere e spegnere il LED
+ digitalWrite(pin, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(velocita); // wait for a second
+ digitalWrite(pin, LOW); // turn the LED off by making the voltage LOW
+ delay(velocita); // wait for a second
+};
+
+void brilla(byte pin, int velocita) {
+ // Accende e spegne il LED accetando un argomento
+ // per impostare la velocita'.
+
+pinMode(pin, OUTPUT);
+ // sequenze di istruzione: accendere e spegnere il LED
+ digitalWrite(pin, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(velocita); // wait for a second
+ digitalWrite(pin, LOW); // turn the LED off by making the voltage LOW
+ delay(velocita); // wait for a second
+};
--- /dev/null
+/*
+ Common Class
+
+ Oggetti comuni
+
+*/
+
+#include "Arduino.h"
+#ifndef common_h
+#define common_h
+
+
+class RGBLed {
+ // Classe rappresentativa di un LED RGB
+
+ byte redPin ;
+ byte greenPin ;
+ byte bluePin ;
+ byte redValue ;
+ byte greenValue ;
+ byte blueValue ;
+
+ public:
+ RGBLed (byte pinR, byte pinG, byte pinB) ;
+ void Red ();
+ void Green ();
+ void Blue ();
+ void Magenta ();
+ void Cyano ();
+ void White ();
+ void Yellow ();
+ void Off ();
+ void SetColor (byte r, byte g, byte b) ;
+};
+
+void brilla(byte pin, int velocita = 500) ;
+
+#endif
--- /dev/null
+/* Esempio
+
+ Come caricare e usare un oggetto e una funzione
+ facente parte della libreria.
+*/
+
+#include <common.h>
+
+void setup() {
+ // I PINs vengono impostati dalla dichiarazione dell'ogetto.
+}
+
+// Instanziamo un LED
+RGBLed led(11, 10, 9); //Istanziamo un oggetto led facente parte
+ // della classe RGBLed
+
+void loop() {
+ led.Red();
+ delay(1000);
+ led.SetColor(255, 0, 255) ; // Mettiamo il LED in Green
+ delay(1000);
+ led.Off();
+
+ brilla(13); // Funzione
+}
--- /dev/null
+RGBLed KEYWORD1
+Red KEYWORD2
+Green KEYWORD2
+Blue KEYWORD2
+Magenta KEYWORD2
+Cyano KEYWORD2
+White KEYWORD2
+Yellow KEYWORD2
+Off KEYWORD2
+SetColor KEYWORD2
+brilla KEYWORD2
// the LED is bigger than the interval at which you want to
// blink the LED.
- if(millis() - previousMillis > interval) {
+ if (millis() > previousMillis + interval) {
// Aggiorniamo il contatore previousMillis
previousMillis = millis();
void loop()
{
// Primo LED
- if(millis() - previousMillisA > intervalA) {
+ if (millis() > previousMillisA + intervalA) {
// save the last time you blinked the LED
previousMillisA = millis();
}
// Secondo LED
- if(millis() - previousMillisB > intervalB) {
+ if (millis() > previousMillisB + intervalB) {
// save the last time you blinked the LED
previousMillisB = millis();
// Funzioni:
void lightLedA () {
- if(millis() - previousMillisA > intervalA) {
+ if (millis() > previousMillisA + intervalA) {
// save the last time you blinked the LED
previousMillisA = millis();
void lightLedB () {
long intervalB = 500;
static int ledStateB ; // https://www.arduino.cc/en/Reference/Static
- if(millis() - previousMillisB > intervalB) {
+ if (millis() > previousMillisB + intervalB) {
// save the last time you blinked the LED
previousMillisB = millis();
void lightLedA (int interval) {
// Illumina il ledA secondo un intervallo passato come argomento
- if(millis() - previousMillisA > interval) {
+ if (millis() > previousMillisA + interval) {
// save the last time you blinked the LED
previousMillisA = millis();
void lightLedB (int interval) {
// Illumina il ledB secondo un intervallo passato come argomento
- if(millis() - previousMillisB > interval) {
+ if (millis() > previousMillisB + interval) {
// save the last time you blinked the LED
previousMillisB = millis();
void lightLedA (int interval) {
// Illumina il ledA secondo un intervallo passato come argomento
- if(millis() - previousMillisA > interval) {
+ if (millis() > previousMillisA + interval) {
// save the last time you blinked the LED
previousMillisA = millis();
void lightLedB (int interval) {
// Illumina il ledB secondo un intervallo passato come argomento
- if(millis() - previousMillisB > interval) {
+ if (millis() > previousMillisB + interval) {
previousMillisB = millis();
digitalWrite(ledB, !digitalRead(ledB));
// Leggiamo direttamente il registro di ledB e scriviamo il suo opposto,
void Update () {
// Illumina il ledB secondo un intervallo passato come argomento
- if(millis() - previousMillis > interval) {
+ if (millis() > previousMillis + interval) {
// save the last time you blinked the LED
previousMillis = millis();
void Update () {
// Illumina il ledB secondo un intervallo passato come argomento
- if(millis() - previousMillis > interval) {
+ if (millis() > previousMillis + interval) {
// save the last time you blinked the LED
previousMillis = millis();
struct blinkLed lightLed(struct blinkLed temp) { // dataType tipo_di_struct nome_funzione(argomenti)
// Illumina il ledA secondo un intervallo passato come argomento
- if(millis() - temp.previousMillis > temp.interval) { // gli elementi dello struct sono accessibili tramite l'operatore [punto]
+ if (millis() > temp.previousMillis + temp.interval) { // gli elementi dello struct sono accessibili tramite l'operatore [punto]
// save the last time you blinked the LED
temp.previousMillis = millis();
long interval ; // milliseconds di intervallo nel lampeggiare
long previousMillis ; //precedente cambio di stato
};
-// Instanziamo i due led dalla struttur
+// Instanziamo i due led dalla struttura
blinkLed ledA = {
13 , LOW , 1000, 0 };
blinkLed ledB = {
--- /dev/null
+/* Blink without Delay
+
+ Turns on and off a light emitting diode(LED) connected to a digital
+ pin, without using the delay() function. This means that other code
+ can run at the same time without being interrupted by the LED code.
+
+ The circuit:
+ * LED attached from pin 13 to ground.
+ * Note: on most Arduinos, there is already an LED on the board
+ that's attached to pin 13, so no hardware is needed for this example.
+
+
+ created 2005
+ by David A. Mellis
+ modified 8 Feb 2010
+ by Paul Stoffregen
+ modified by eaman
+
+ This example code is in the public domain.
+
+
+ http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
+ */
+
+// constants won't change. Used here to
+// set pin numbers:
+const int ledPin = 13;
+
+// Variables will change:
+int ledState = LOW; // ledState used to set the LED
+long previousMillis = 0; // will store last time LED was updated
+
+// the follow variables is a long because the time, measured in miliseconds,
+// will quickly become a bigger number than can be stored in an int.
+const long interval = 1000; // interval at which to blink (milliseconds)
+
+void setup() {
+ // set the digital pin as output:
+ pinMode(ledPin, OUTPUT);
+}
+
+void loop()
+{
+ // here is where you'd put code that needs to be running all the time.
+
+ // check to see if it's time to blink the LED; that is, if the
+ // difference between the current time and last time you blinked
+ // the LED is bigger than the interval at which you want to
+ // blink the LED.
+
+ if (millis() > previousMillis + interval) {
+ // Aggiorniamo il contatore previousMillis
+ previousMillis = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledState == LOW)
+ ledState = HIGH;
+ else
+ ledState = LOW;
+ // e' possibile semplificare questa operazione?
+ // Hint: lo stato del LED e' binario: ha solo due stati possibili.
+
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledPin, ledState);
+ }
+}
+
+/* Domande
+ 1. Aggioungere un LED che brilli ogni 500ms
+ 2. E' ora agevole cambiare gli intervalli dei due LED?
+ Modificare gli intervalli dei due led (es 500ms - 320ms)
+ */
--- /dev/null
+/* Blink without Delay - due led
+
+ Turns on and off a light emitting diode(LED) connected to a digital
+ pin, without using the delay() function. This means that other code
+ can run at the same time without being interrupted by the LED code.
+
+ The circuit:
+ * LED attached from pin 13 to ground.
+ * Note: on most Arduinos, there is already an LED on the board
+ that's attached to pin 13, so no hardware is needed for this example.
+
+
+ created 2005
+ by David A. Mellis
+ modified 8 Feb 2010
+ by Paul Stoffregen
+ modified by eaman
+
+ This example code is in the public domain.
+
+
+ http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
+ */
+
+// constants won't change. Used here to
+// set pin numbers:
+const int ledA = 13; // Primo LED
+const int ledB = 12; // Secondo LED
+
+// Variabbili di stato
+int ledStateA = LOW; // ledState used to set the LED
+int ledStateB = LOW; // ledState used to set the LED
+
+long previousMillisA = 0; // will store last time LED was updated
+long previousMillisB = 0; // will store last time LED was updated
+
+// the follow variables is a long because the time, measured in miliseconds,
+// will quickly become a bigger number than can be stored in an int.
+long intervalA = 1000; // interval at which to blink (milliseconds)
+long intervalB = 500; // interval at which to blink (milliseconds)
+
+void setup() {
+ // set the digital pin as output:
+ pinMode(ledA, OUTPUT);
+ pinMode(ledB, OUTPUT);
+}
+
+void loop()
+{
+// Primo LED
+ if (millis() > previousMillisA + intervalA) {
+ // save the last time you blinked the LED
+ previousMillisA = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateA == LOW)
+ ledStateA = HIGH;
+ else
+ ledStateA = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledA, ledStateA);
+ }
+
+// Secondo LED
+ if (millis() > previousMillisB + intervalB) {
+ // save the last time you blinked the LED
+ previousMillisB = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateB == LOW)
+ ledStateB = HIGH;
+ else
+ ledStateB = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledB, ledStateB);
+ }
+}
+
+/* Domande
+ 1. Provare a isolare il codice per accendere ogni singolo led in una funzione:
+ - Quali variabili determinano il comportamento del LED?
+ - Come cambiano durante il corso dello script?
+ - Sono globali o locali?
+ - Quali parti vanno eseguite una sola volta e quali a ogni esecuzione?
+ */
+
+
+
--- /dev/null
+/* Blink without Delay
+
+ Blink con funzione
+
+ Soluzione: Provare a isolare il codice per accendere ogni singolo led in una funzione:
+
+ - Quali variabili determinano il comportamento del LED?
+ - Come cambiano durante il corso dello script?
+ - Sono globali o locali?
+
+ */
+
+/////////////
+// First LED
+const int ledA = 13; // the number of the LED pin
+// Variables will change:
+int ledStateA = LOW; // ledState used to set the LED
+long previousMillisA = 0; // will store last time LED was updated
+// the follow variables is a long because the time, measured in miliseconds,
+// will quickly become a bigger number than can be stored in an int.
+long intervalA = 1000; // interval at which to blink (milliseconds)
+void lightLedA () ;
+
+//////////////
+// Second LED
+// Now with less global variables thanks to static (see function body)
+const int ledB = 12; //Secondo LED
+ // ledState used to set the LED
+long previousMillisB = 0; // will store last time LED was updated
+ // interval at which to blink (milliseconds)
+void lightLedB () ;
+
+
+void setup() {
+ // set the digital pin as output:
+ pinMode(ledA, OUTPUT);
+ pinMode(ledB, OUTPUT);
+}
+
+void loop()
+{
+ lightLedA();
+ lightLedB();
+}
+
+
+// Funzioni:
+
+void lightLedA () {
+ if (millis() > previousMillisA + intervalA) {
+ // save the last time you blinked the LED
+ previousMillisA = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateA == LOW)
+ ledStateA = HIGH;
+ else
+ ledStateA = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledA, ledStateA);
+ }
+
+}
+
+void lightLedB () {
+ long intervalB = 500;
+ static int ledStateB ; // https://www.arduino.cc/en/Reference/Static
+ if (millis() > previousMillisB + intervalB) {
+ // save the last time you blinked the LED
+ previousMillisB = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateB == LOW)
+ ledStateB = HIGH;
+ else
+ ledStateB = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledB, ledStateB);
+ }
+}
+
+
+/* Domande
+ 1. Modificare le funzioni in modo che accettino come parametro
+ l'intervallo di lampeggio.
+
+ */
+
+
+
+
+
+
--- /dev/null
+/* Blink without Delay
+ Soluzione
+
+ Introdotto un argomento per la funzione che nodifica l'intervallo di lampeggio
+
+ */
+
+// First LED
+int ledA = 13; // the number of the LED pin
+// Variables will change:
+int ledStateA = LOW; // ledState used to set the LED
+long previousMillisA = 0; // will store last time LED was updated
+
+// Second LED data
+int ledB = 12; //Secondo LED
+int ledStateB = LOW; // ledState used to set the LED
+long previousMillisB = 0; // will store last time LED was updated
+
+void setup() {
+ // set the digital pin as output:
+ pinMode(ledA, OUTPUT);
+ pinMode(ledB, OUTPUT);
+}
+
+void loop()
+{
+ lightLedA(333);
+ lightLedB(500);
+}
+
+//////////////
+// Funzioni
+
+void lightLedA (int interval) {
+ // Illumina il ledA secondo un intervallo passato come argomento
+
+ if (millis() > previousMillisA + interval) {
+ // save the last time you blinked the LED
+ previousMillisA = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateA == LOW)
+ ledStateA = HIGH;
+ else
+ ledStateA = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledA, ledStateA);
+ }
+
+}
+
+void lightLedB (int interval) {
+ // Illumina il ledB secondo un intervallo passato come argomento
+
+ if (millis() > previousMillisB + interval) {
+ // save the last time you blinked the LED
+ previousMillisB = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ if (ledStateB == LOW)
+ ledStateB = HIGH;
+ else
+ ledStateB = LOW;
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledB, ledStateB);
+ }
+}
+
+/* Approfondimenti
+- Quali similitudini ci sono tra le due funzioni?
+- Distinguere i dati comuni tra le due funzioni che ci servono per
+ far lampeggiare i LED
+- Distinguere i dati che caratterizzano un LED rispetto all'altro
+- Provare a integrare le variabili relative ai due LED dentro le
+ rispettive funzioni.
+- Sarebbe possibile scrivere una funzione che possa interagire con un LED qualunque?
+ ES: Come inpostare il PIN del LED? Come gestire lo stato del LED?
+*/
+
+
+
+
+
+
+
--- /dev/null
+/* Blink without Delay - Pulizia
+
+Semplificato il ciclo condizionale, la seconda funzione non necessita
+di una variabile di stato per tracciare il LED.
+
+ */
+
+// constants won't change. Used here to
+// set pin numbers:
+
+// First LED
+const int ledA = 13; // the number of the LED pin
+// Variables will change:
+int ledStateA = LOW; // ledState used to set the LED
+long previousMillisA = 0; // will store last time LED was updated
+
+// Second LED data
+const int ledB = 12; //Secondo LED
+// int ledStateB = LOW; // Possiamo leggere lo stato del registro del LED
+ // con digitalRead()
+long previousMillisB = 0; // will store last time LED was updated
+
+void setup() {
+ // set the digital pin as output:
+ pinMode(ledA, OUTPUT);
+ pinMode(ledB, OUTPUT);
+}
+
+void loop()
+{
+ lightLedA(1000);
+ lightLedB(500);
+}
+
+////////////////
+// Funzioni
+
+void lightLedA (int interval) {
+ // Illumina il ledA secondo un intervallo passato come argomento
+
+ if (millis() > previousMillisA + interval) {
+ // save the last time you blinked the LED
+ previousMillisA = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ ledStateA = !ledStateA ; // Inverti il LED
+ }
+ digitalWrite(ledA, ledStateA);
+}
+
+void lightLedB (int interval) {
+ // Illumina il ledB secondo un intervallo passato come argomento
+
+ if (millis() > previousMillisB + interval) {
+ previousMillisB = millis();
+ digitalWrite(ledB, !digitalRead(ledB));
+ // Leggiamo direttamente il registro di ledB e scriviamo il suo opposto,
+ // questo ci permette di non dover avere una variabile per tracciare lo stato.
+ }
+}
+/* Domande:
+ 1. E' possibile avere una sola funzione che permetta di gestire
+ qualunque LED io voglia aggiungere?
+
+/* Approfondimenti
+ - integrazione tra funzioni e dati: programmazione a oggetti
+ - Uso di pointers per modificare dati esterni allo scope della funzione, static
+ - Uso di forme di dati strutturate (array, struct) per scambiare dati tra funzioni e programma
+ */
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null
+/* Blink without Delay
+ Class: definizione di una classe LED.
+
+ L'oggetto LED integra i dati (proprieta') del led con i metodi (le funzioni).
+ */
+
+// Oggetti:
+class Lampeggiatore {
+ // Lampeggia un LED utilizzando millis()
+ // Variabili
+ int ledPin ; // il numero del LED pin
+ int ledState ; // stato attuale del LED
+ long interval ; // milliseconds di intervallo nel lampeggiare
+ long previousMillis ; // precedente cambio di stato
+
+ // Constructor: come viene instanziato un oggetto facente parte della classe
+public:
+ Lampeggiatore(int pin, long time)
+ {
+ ledPin = pin;
+ pinMode(ledPin, OUTPUT);
+ ledState = LOW;
+ previousMillis = 0;
+ interval = time;
+ }
+
+// Una funzione facente parte di una classe prende il nome di "metodo" della stessa:
+ void Update () {
+ // Illumina il ledB secondo un intervallo passato come argomento
+
+ if (millis() > previousMillis + interval) {
+ // save the last time you blinked the LED
+ previousMillis = millis();
+
+ // if the LED is off turn it on and vice-versa:
+ ledState = !ledState ; // Inverti il LED
+ }
+ // set the LED with the ledState of the variable:
+ digitalWrite(ledPin, ledState);
+ }
+
+};
+
+// Instanziamo i due led dalla classe
+Lampeggiatore ledA(13, 1000);
+Lampeggiatore ledB(12, 500);
+
+void setup() {
+}
+
+void loop()
+{
+ledA.Update();
+ledB.Update();
+}
+
+/* Domande:
+ 1. Ogni quante volte viene eseguito il codice del loop per ogni millisecondo?
+ 2. Utilizzare un interrupt per richiamare Update()
+ Es: https://learn.adafruit.com/multi-tasking-the-arduino-part-2/overview
+ */
+
--- /dev/null
+/*
+ Blink
+ Turns on an LED on for one second, then off for one second, repeatedly.
+
+ This example code is in the public domain.
+ */
+
+// Pin 13 has an LED connected on most Arduino boards.
+// give it a name:
+int led = 13;
+
+// the setup routine runs once when you press reset:
+void setup() {
+ // initialize the digital pin as an output.
+ pinMode(led, OUTPUT);
+}
+
+// the loop routine runs over and over again forever:
+void loop() {
+ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
+ delay(1000); // wait for a second
+ digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
+ delay(1000); // wait for a second
+}
+
+/* Domande
+ 1. Aggiungere un secondo LED e farlo brillare ogni 500ms
+ mentre il primo brilla ogni 1000ms
+ 2. Cosa succederebbe se dovessi anche leggere un input da un sensore / bottone?
+ */
+
--- /dev/null
+/*
+ Blink due LED - Soluzione
+
+ Aggiungere un secondo LED e farlo brillare ogni 500ms
+ mentre il primo brilla ogni 1000ms
+
+ Massimo comun denominatore 1000 MCD 500 = 500ms
+ Durata Periodo = 500ms
+
+
+ Stati:
+
+ a | b Changes
+ ======== =========
+ 1 | 1 x | x
+ 1 | 0 | x
+ 0 | 1 x | x
+ 0 | 0 | x
+
+
+ */
+
+// Pin 13 has an LED connected on most Arduino boards.
+// give it a name:
+const int ledA = 13; //Primo LED
+const int ledB = 12; //Secondo LED, con resistenza
+
+// the setup routine runs once when you press reset:
+void setup() {
+ // initialize the digital pin as an output.
+ pinMode(ledA, OUTPUT);
+ pinMode(ledB, OUTPUT);
+}
+
+// the loop routine runs over and over again forever:
+void loop() {
+ // Primo periodo
+ digitalWrite(ledA, HIGH); // turn the LED on (HIGH is the voltage level)
+ digitalWrite(ledB, HIGH);
+ delay(500); // Minimo comun denominatore del periodo
+
+ // Secondo periodo
+ //digitalWrite(ledA, HIGH); // ledA non cambia
+ digitalWrite(ledB, LOW);
+ delay(500);
+
+ // Terzo periodo
+ digitalWrite(ledA, LOW);
+ digitalWrite(ledB, HIGH);
+ delay(500);
+
+ // Quarto periodo
+ //digitalWrite(ledA, LOW);
+ digitalWrite(ledB, LOW);
+ delay(500);
+}
+
+/* Domande
+ 1. Altro scenartio: fare brillare un LED ogni 300ms mentre il secondo brilla ogni 400m
+ 2. Aggiungere un terzo LED
+ */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+++ /dev/null
-/*
- Blink v5
-
- Accensione e spegnimanto di 2 LED.
- Nel circuito oltre al LED montato direttamente sul pin 13
- viene aggiunto un altro LED pilotato dal PIN 12.
-
- Ricordarsi di usare una resistenza da ~320ohms per il secondo LED.
- Resistenza = (Voltaggio_Arduino - Forward_voltage_LED) / (ampere utilizzati)
- R = (5v-1.8v) / 0.010a
- R =320ohms
-
-
- Schema: http://lab.piffa.net/schemi/led_single_bb.png
- - http://lab.piffa.net/schemi/led_single_schem.png
-
- This example code is in the public domain.
- */
-
-
-int led = 13; // Il LED onboard corrisponde al PIN 13
- // Ha una resistenza premontata
-int red = 12; // Definiamo un altro led
-int breve = 200; // Variabile richiambile nel corso dell'esecuzione
-int lunga = 1000;
-
-// /////////////////
-// Setup: eseguita una volta sola all'accensione della scheda
-void setup() {
- // initialize the digital pin as an output.
- pinMode(led, OUTPUT); // Abilitaiamo entrambi i LED
- pinMode(red, OUTPUT);
-}
-
-// ///////////////
-// loop: Le istruzioni vengono eseguite all'infinito
-void loop() {
- digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(breve); // wait for a second
- digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
- delay(breve); // wait for a second
-
- digitalWrite(red, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(lunga); // wait for a second
- digitalWrite(red, LOW); // turn the LED off by making the voltage LOW
- delay(lunga);
-}
-
-/* Domande
- *
- * 1. Creare una funzione che sia slegata dal PIN con cui interagisce.
- *
- * 2. Come procede il flusso delle istruzioni per far brillare i LED?
- * E' possibile far brillare i LED indipendentemente l'uno dall'altro?
- *
- *
- * Nota: la risposta alla domanda 2 arrivera' a fine corso!
- */
-
-
-
-
-
-
-
+++ /dev/null
-/*
- Input Condizionale
-
- Accensione e spegnimanto di un LED utilizzando un pin come input.
-
- Utilizzare un jumper per collegare il PIN Input
- alternativamente a +5 o GND .
-
-Schema:
-- http://lab.piffa.net/schemi/led_condizionale.png
-
- */
-
-// Pin 13 has an LED connected on most Arduino boards.
-// give it a name:
-int led = 12;
-int input = 2;
-
-// the setup routine runs once when you press reset:
-void setup() {
- // initialize the digital pin as an output.
- pinMode(led, OUTPUT); // Il PIN e' attivato come output
- pinMode(input, INPUT); // Il PIN e' attivato come output
-}
-
-// the loop routine runs over and over again forever:
-void loop() {
- if (digitalRead(input) == HIGH) { // Verifica se il PIN input e' +5V
- digitalWrite(led, HIGH);
- }
- if (digitalRead(input) == LOW) { // Verifica se il PIN input e' 0V
- digitalWrite(led, LOW);
- }
-}
-
-/* Domande:
- 1. Invertire il programma facendo in modo che il led si spenga
- quando il bottone e' premuto. Considerare come ottenere lo stesso risultato
- modificando il circuito.
- 2. Modificare il programma per far brillare il led cinque volte al secondo
- quando il bottone e' premuto.
- 3. Si potrebbe usare un ciclo iterativo while invece che
- un ciclo condizonale if? Che differenza c'e' tra il ciclo while e for?
- 4. Domanda: cosa succede se il jumper input non e' collegato ne al +5 ne al ground?
- */
+++ /dev/null
-/*
- Input serial debug
-
-
- Accensione e spegnimanto di un LED utilizzando un pin come input.
- Utilizzare un bottone momentaneo per attivare il LED.
-
- Schemi del circuito per bottone in pull down:
- - http://lab.piffa.net/schemi/button_1_bb.png
- - http://lab.piffa.net/schemi/button_1_schem.png
-
-Tutorial:
--
- */
-
-int led = 12;
-int input = 2;
-
-// the setup routine runs once when you press reset:
-void setup() {
- pinMode(led, OUTPUT); // Il PIN e' attivato come output
- pinMode(input, INPUT); // Il PIN e' attivato come output
-
- Serial.begin(9600); // Attivazione seriale
-}
-
-// the loop routine runs over and over again forever:
-void loop() {
- if (digitalRead(input) == HIGH) { // Verifica se il PIN input e' +5v
- digitalWrite(led, HIGH);
- Serial.println("Bottone premuto: circuito chiuso"); // Debug seriale
- delay(200);
- }
- else { // Alterativa: se non e' +5v
- digitalWrite(led, LOW);
- Serial.println("Bottone libero: circuito aperto"); // Debug seriale
- delay(200);
- }
-}
-
-/* Domande:
- 1. invertire il programma facendo in modo che il led si spenga
- quando il bottone e' premuto. Consoderare come ottenere lo stesso risultato
- modificando il circuito.
- 2. Modificare il programma per far brillare il led cinque volte al secondo
- quando il bottone e' premuto.
- 3. Si potrebbe usare un ciclo iterativo while invece che
- un ciclo condizonale if? Che differenza c'e' tra il ciclo while e for?
- 4. Domanda: cosa succede se il jumper input non e' collegato ne al +5 ne al gound?
- */
--- /dev/null
+/* Knight Rider 1
+ * --------------
+ *
+ * Basically an extension of Blink_LED.
+ *
+ *
+ * (cleft) 2005 K3, Malmo University
+ * @author: David Cuartielles
+ * @hardware: David Cuartielles, Aaron Hallborg
+ See: https://www.arduino.cc/en/Tutorial/KnightRider
+
+ Schema semplificato:
+ - http://lab.piffa.net/schemi/8_led_single_res_bb.png
+ - http://lab.piffa.net/schemi/8_led_single_res_schem.png
+ */
+
+int pin2 = 2;
+int pin3 = 3;
+int pin4 = 4;
+int pin5 = 5;
+int pin6 = 6;
+int pin7 = 7;
+int pin8 = 8;
+int pin9 = 9;
+int timer = 100;
+
+void setup(){
+ pinMode(pin2, OUTPUT);
+ pinMode(pin3, OUTPUT);
+ pinMode(pin4, OUTPUT);
+ pinMode(pin5, OUTPUT);
+ pinMode(pin6, OUTPUT);
+ pinMode(pin7, OUTPUT);
+ pinMode(pin8, OUTPUT);
+ pinMode(pin9, OUTPUT);
+}
+
+void loop() {
+ digitalWrite(pin2, HIGH);
+ delay(timer);
+ digitalWrite(pin2, LOW);
+ delay(timer);
+
+ digitalWrite(pin3, HIGH);
+ delay(timer);
+ digitalWrite(pin3, LOW);
+ delay(timer);
+
+ digitalWrite(pin4, HIGH);
+ delay(timer);
+ digitalWrite(pin4, LOW);
+ delay(timer);
+
+ digitalWrite(pin5, HIGH);
+ delay(timer);
+ digitalWrite(pin5, LOW);
+ delay(timer);
+
+ digitalWrite(pin6, HIGH);
+ delay(timer);
+ digitalWrite(pin6, LOW);
+ delay(timer);
+
+ digitalWrite(pin7, HIGH);
+ delay(timer);
+ digitalWrite(pin7, LOW);
+ delay(timer);
+
+ digitalWrite(pin8, HIGH);
+ delay(timer);
+ digitalWrite(pin8, LOW);
+ delay(timer);
+
+ digitalWrite(pin9, HIGH);
+ delay(timer);
+ digitalWrite(pin9, LOW);
+ delay(timer);
+
+ // Ding! Mezzo giro
+
+ digitalWrite(pin8, HIGH);
+ delay(timer);
+ digitalWrite(pin8, LOW);
+ delay(timer);
+
+ digitalWrite(pin7, HIGH);
+ delay(timer);
+ digitalWrite(pin7, LOW);
+ delay(timer);
+
+ digitalWrite(pin6, HIGH);
+ delay(timer);
+ digitalWrite(pin6, LOW);
+ delay(timer);
+
+ digitalWrite(pin5, HIGH);
+ delay(timer);
+ digitalWrite(pin5, LOW);
+ delay(timer);
+
+ digitalWrite(pin4, HIGH);
+ delay(timer);
+ digitalWrite(pin4, LOW);
+ delay(timer);
+
+ digitalWrite(pin3, HIGH);
+ delay(timer);
+ digitalWrite(pin3, LOW);
+ delay(timer);
+}
--- /dev/null
+/* Knight Rider 2
+ * --------------
+ *
+ * Array e uso dei cicli iterativi.
+ *
+
+
+ Schema semplificato:
+ - http://lab.piffa.net/schemi/8_led_single_res_bb.png
+ - http://lab.piffa.net/schemi/8_led_single_res_schem.png
+ */
+
+int pinArray[8] = {2, 3, 4, 5, 6, 7, 8, 9};
+int timer = 100;
+
+void setup(){
+ // we make all the declarations at once
+ for (int count=0;count<9;count++) {
+ pinMode(pinArray[count], OUTPUT);
+ }
+}
+
+void loop() {
+ for (int count=0;count<8;count++) { // 8 e' un numero magico
+ digitalWrite(pinArray[count], HIGH);
+ delay(timer);
+ digitalWrite(pinArray[count], LOW);
+ delay(timer);
+ }
+
+// Ciclo inverso: dall'alto in basso
+ for (int count=8;count>=0;count--) {
+ digitalWrite(pinArray[count], HIGH);
+ delay(timer);
+ digitalWrite(pinArray[count], LOW);
+ delay(timer);
+ }
+}
+
+/* Domande:
+
+ 1. Come posso fare per saltare un elemento del loop?
+ 2. Come posso fare per uscire completamente dal loop?
+ 3. 8 e' un numero magico: come posso evitarlo?
+
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+.
+Soluzioni:
+ 1. utilizzare continue
+ 2. utilizzare break
+ 3. Utilizzare un variabile sarebbe gia' un inizio, ancora meglio estrarre il
+ valore tramite la funzione sizeof().
+Links:
+- http://www.tutorialspoint.com/cprogramming/c_continue_statement.htm
+- https://www.arduino.cc/en/Reference/Sizeof
+*/
+
+
--- /dev/null
+/*
+ For Loop Iteration
+
+ Demonstrates the use of a for() loop.
+ Lights multiple LEDs in sequence, then in reverse.
+
+ The circuit:
+ * LEDs from pins 2 through 9 to ground
+
+ Schemi:
+ - http://lab.piffa.net/schemi/8_led_single_res_bb.png
+ - http://lab.piffa.net/schemi/8_led_single_res_schem.png
+
+ http://www.arduino.cc/en/Tutorial/ForLoop
+ */
+
+byte ledPins[8] = { // Domanda: cosa succede se uso int?
+ 2,3,4,5,6,7,8,9}
+; //Array
+int timer = 100; // Pausa per far brillare i LED
+
+void setup() {
+ Serial.begin(9600);
+ // use a for loop to initialize each pin as an output:
+ for (int thisPin = 0; thisPin < sizeof(ledPins); thisPin++) {
+ pinMode(ledPins[thisPin], OUTPUT);
+ Serial.print("Inizializzato pin n. ");
+ Serial.println( thisPin);
+ }
+
+ Serial.print("Dimesione array: ");
+ Serial.println(sizeof(ledPins));
+}
+
+void loop() {
+ // loop from the lowest pin to the highest:
+ for (int thisPin = 0; thisPin < sizeof(ledPins); thisPin++) {
+ Serial.print("Accensione pin n. ");
+ Serial.println(thisPin);
+ // turn the pin on:
+ digitalWrite(ledPins[thisPin], HIGH);
+ delay(timer);
+ // turn the pin off:
+ digitalWrite(ledPins[thisPin], LOW);
+ // Debug
+
+ }
+
+ // loop from the highest pin to the lowest:
+ for (int thisPin = sizeof(ledPins) -1 ; thisPin > 0; thisPin--) {
+ Serial.print("Accensione pin n. "); // Gli array sono indicizzati da 0
+ Serial.println(thisPin);
+ digitalWrite(ledPins[thisPin], HIGH);
+ delay(timer);
+ digitalWrite(ledPins[thisPin], LOW);
+
+ }
+}
+++ /dev/null
-/*
- * Hello World!
- *
- * This is the Hello World! for Arduino.
- * It shows how to send data to the computer trough the serial connection
- */
-
-void setup()
-{
- Serial.begin(9600); // Inposta la seriale a 9600 bps
- // Se Arduino manda 9600 bit per secondo e devi manandare 12 Bytes di dati
- // quanto tempo serve per mandare i dati?
-
- // Try to change bond rate in the monitor
-
- Serial.println("Hello World!"); // scrive hello world e ritorna a capo
-
-
-// Serial.print("Il mio nome e': "); // Scrive senza ritorno a capo
-// Serial.println("Andrea"); // Scrive con ritorno a capo
-// Serial.flush(); // Assicura che tutto il testo venga scritto
-
-}
-
-void loop()
-{
- // Provate a mettere i Serial.printl() qui, magari con un delay()
-}
-
-
-
-
+++ /dev/null
-/*
- * Switch test program
- */
-
-int switchPin = 2; // Switch connected to digital pin 2
-
-void setup() // run once, when the sketch starts
-{
- Serial.begin(9600); // set up Serial library at 9600 bps
- pinMode(switchPin, INPUT); // sets the digital pin as input to read switch
-}
-
-
-void loop() // run over and over again
-{
- Serial.print("Read switch input: ");
- Serial.println(digitalRead(switchPin)); // Read the pin and display the value
- delay(200);
-}
for (int thisPin = sizeof(ledPins) -1 ; thisPin > 0; thisPin--) {
Serial.print("Accensione pin n. "); // Gli array sono indicizzati da 0
Serial.println(thisPin);
- // ><<turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
- // turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
-
-
-