]> git.piffa.net Git - sketchbook_andrea/blob - serial/i2c/master_3_feedback/master_3_feedback.ino
serial + i2c
[sketchbook_andrea] / serial / i2c / master_3_feedback / master_3_feedback.ino
1 /*
2   I2C comm: Master
3  
4  Comunicazione I2C tra due schede Arduino.
5  La  scheda master ha un bottone come input e 
6  comunica con altre schede che monta un LED come output.
7  Il led della seconda si accende quando rileva
8  la pressione del bottone della prima.
9  
10  Questo script implementa il debounce con Millis()
11  
12  Schema: http://lab.piffa.net/schemi/i2c_bb.jpg
13  */
14
15 #include <Wire.h>
16
17 int led = 13;
18 int input = 2;  // Questa e' la scheda con un input           
19 int statoAttuale;                        // variable for reading the pin status
20 int ultimoStato;                // variable to hold the last button state
21 long ultimoCambio = 0;  // Momento in cui e' stato attivato il PIN input
22 long debounceDelay = 100;    // Tempo di debounce
23
24 // the setup routine runs once when you press reset:
25 void setup() {                
26   // initialize the digital pin as an output.
27   pinMode(led, OUTPUT);       // Il PIN e' attivato come output
28   pinMode(input, INPUT_PULLUP);        // Il PIN e' attivato come output
29
30   Serial.begin(9600); // Attiviamo la seriale per debug
31   Serial.flush();
32   Serial.println("Master Debug:");
33
34   // Serial.begin(9600); // Attiviamo la seriale per debug
35   Wire.begin(); // join i2c bus (address optional for master)
36 }
37
38
39 void loop() {
40   statoAttuale = digitalRead(input);      // Legge lo stato del bottone
41
42   if (statoAttuale == LOW && statoAttuale != ultimoStato && millis() - ultimoCambio > debounceDelay ) {
43     // Trasmissione I2C
44     Wire.beginTransmission(2); // Invia il messaggio al device slave con id 2
45     Wire.write("1");
46     Wire.endTransmission();    // stop transmitting
47
48     // Gestone stato
49     ultimoCambio = millis() ;    // Registra il tempo attuale
50
51
52     // Request per lo stato del LED
53     delay(100);
54     Wire.requestFrom(2,1);
55     while(Wire.available())    // slave may send less than requested
56     {
57       char statoRemoto = Wire.read(); // receive a byte as character
58       Serial.print("Stato del LED sul device 2: ");
59       Serial.println(statoRemoto,DEC);         // print the character
60     }
61   }
62   ultimoStato = statoAttuale;                 // save the new state in our variable
63
64
65
66 }
67
68 /* Domande
69  
70  1. Implementare piu' bottoni per controllare piu' schede
71  2. Isolare (per quanto possibile) la gestione di un BOTTONE-LED in una funzione 
72     (es multitasking/BlinkWithoutDelay_3_funzione )
73  3. Costruire una classi (programmazione ad oggetti) per l'oggetto BOTTONE-LED
74     (es: multitasking/BlinkWithoutDelay_6_class/ )
75  
76  */
77
78
79
80
81