]> git.piffa.net Git - sketchbook_andrea/blob - serial/i2c/slave_3_feedback/slave_3_feedback.ino
serial + i2c
[sketchbook_andrea] / serial / i2c / slave_3_feedback / slave_3_feedback.ino
1 /*
2   I2C comm: Slave LED
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  Schema: http://lab.piffa.net/schemi/i2c_bb.jpg
11  */
12
13 #include <Wire.h>
14 //  slave
15 // PIN 0 = RX
16 int led = 13; // Questa scheda ha spolo l'output
17 int ledState = 0;         // stato attuale del LED
18 int incomingByte;   // Dato ricevuto via seriale
19
20
21 // the setup routine runs once when you press reset:
22 void setup() {                
23   // initialize the digital pin as an output.
24   pinMode(led, OUTPUT);       // Il PIN e' attivato come output
25
26   Serial.begin(9600); // Attiviamo la seriale per debug
27   Serial.flush();
28   Serial.println("Slave / RX Debug:");
29   
30   Wire.begin(2); // join i2c bus (address optional for master)
31   Wire.onReceive(receiveEvent); // Evento in ricezione dati
32   Wire.onRequest(requestCallback); // Evento su richiesta
33 }
34
35
36 void loop() {
37   digitalWrite(led, ledState); // Aggiorna lo stato del LED
38   delay(200);
39 }
40
41 /// Funzioni
42 void receiveEvent(int howMany)
43 {
44   Serial.print("Lo slave ha ricevuto il seguente messaggio: ");
45   while( Wire.available()) // loop through all but the last
46   {
47     incomingByte = Wire.read(); // receive byte as a character
48     Serial.print(incomingByte, DEC);         // print the character
49
50     if (incomingByte == 49) { // Verifica se viene ricevuto il dato 1
51       ledState = !ledState ; // Cambia lo stato del LED 
52     }        
53     Serial.println("");
54   }
55 }
56
57 void requestCallback()
58 {
59   // Rimanda lo stato del LED
60   Serial.println("Comunicato lo stato del LED a MASTER"); // Debug
61  
62   Wire.write(ledState);
63 }
64
65 /* Domande
66  
67  1. Implementare piu' bottoni per controllare piu' schede
68  2. Isolare (per quanto possibile) la gestione di un BOTTONE-LED in una funzione 
69     (es multitasking/BlinkWithoutDelay_3_funzione )
70  3. Costruire una classi (programmazione ad oggetti) per l'oggetto BOTTONE-LED
71     (es: multitasking/BlinkWithoutDelay_6_class/ )
72  
73  */
74  
75
76
77
78
79
80
81