]> git.piffa.net Git - sketchbook_andrea/blob - serial/i2c/master_2_led/master_2_led.ino
serial + i2c
[sketchbook_andrea] / serial / i2c / master_2_led / master_2_led.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
13 #include <Wire.h>
14
15 int led = 13;
16 int input = 2;  // Questa e' la scheda con un input           
17 int statoAttuale;                        // variable for reading the pin status
18 int ultimoStato;                // variable to hold the last button state
19 long ultimoCambio = 0;  // Momento in cui e' stato attivato il PIN input
20 long debounceDelay = 100;    // Tempo di debounce
21
22 // the setup routine runs once when you press reset:
23 void setup() {                
24   // initialize the digital pin as an output.
25   pinMode(led, OUTPUT);       // Il PIN e' attivato come output
26   pinMode(input, INPUT_PULLUP);        // Il PIN e' attivato come output
27
28  // Serial.begin(9600); // Attiviamo la seriale per debug
29   Wire.begin(); // join i2c bus (address optional for master)
30 }
31
32
33 void loop() {
34   statoAttuale = digitalRead(input);      // Legge lo stato del bottone
35
36   if (statoAttuale == LOW && statoAttuale != ultimoStato && millis() - ultimoCambio > debounceDelay ) {
37     // Trasmissione I2C
38     Wire.beginTransmission(2); // Invia il messaggio al device slave con id 2
39     Wire.write("1");
40     Wire.endTransmission();    // stop transmitting
41     
42     // Gestone stato
43     ultimoCambio = millis() ;    // Registra il tempo attuale
44   }
45   ultimoStato = statoAttuale;                 // save the new state in our variable
46 }
47
48 /* Domande
49  
50  1. Implementare piu' bottoni per controllare piu' schede
51  2. Implementare un messaggio di feedback dallo slave al master per uk cambio di stato del led  
52  
53  Links:
54
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  Risposte in fondo:
65  1. Vedere i links proposti: .write scrive un byte mentre
66  .print manda un codice ASCII
67  2. 49
68  3. No, dato solo il cavo dalla TX alla RX .
69  Provare a fare un script con comunicazione bilaterale
70  4. No perche' non ci sarebbe sincronia tra i segnali,
71  vedere gli esercizi su I2C
72  */
73
74