Arduino > Exemple I2C Arduino esclave

1.  Description

Voir: http://arduino.cc/en/Tutorial/MasterWriter

2.  Branchement

3.  Code Arduino maître

#include <Wire.h>

byte x = 0;

unsigned long lastLEDMillis;
unsigned long lastButtonMillis;

byte buttonState;

void setup()
{
        Serial.begin(57600);
        Wire.begin(); // join i2c bus (address optional for master)
}


void loop()
{



        if ( millis() > lastLEDMillis + 1000 ) {
                lastLEDMillis = millis();

                Wire.beginTransmission(4); // transmit to device #4
                Wire.write(x);        // sends one byte
                Wire.endTransmission();    // stop transmitting

                if ( x == 0 ) x = 1;
                else x = 0;

        }


        if ( millis() > lastButtonMillis + 10 ) {
                lastButtonMillis = millis();
                Wire.requestFrom(4,1); // Request 1 byte from device #4
        }

        // Process received data
        while ( Wire.available() > 0 ) {

                byte data = Wire.read();

                if ( data != buttonState ) {

                        buttonState = data;

                        if ( buttonState == 1 ) Serial.print("HIGH");
                        else Serial.print("LOW");

                        Serial.println();
                }
        }

}

4.  Code Arduino esclave

#include <Wire.h>


void setup()
{
        Wire.begin(4);                // join i2c bus with address #4
        Wire.onReceive(receiveEvent); // register event
        Wire.onRequest(requestEvent);


        pinMode(13,OUTPUT);


        pinMode(12,INPUT);
        digitalWrite(12,HIGH); // Internal pull-up


}

void loop()
{

}


// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{

        byte x = Wire.read();    // receive byte
        if ( x == 0 ) digitalWrite(13,LOW);
        else digitalWrite(13,HIGH);

}

// function to be called when a master requests data from this slave device
// this function is registered as an event, see setup()
void requestEvent( ) {

        byte buttonState = digitalRead(12);

        if ( buttonState == HIGH ) Wire.write( 1 );
        else Wire.write( 0 );

}