#include <Wire.h>
// Declare variables
int x = 0;
bool button = false;
void setup() {
// Initialize I2C communication with address 2
Wire.begin(2);
// Register the "dato" function to be called
//when data is received
Wire.onReceive(dato);
// Register the "event" function to be called
//when data is requested
Wire.onRequest(event);
// Initialize serial communication at 9600 bps
Serial.begin(9600);
// Set pin 4 as output for the LED
pinMode(4, OUTPUT);
// Set pin 0 as input for the button
pinMode(0, INPUT);
}
void loop() {
// Check if the button is pressed (digital read
//from pin 0 is HIGH)
if (digitalRead(0) == 1) {
digitalWrite(4, 1); // Turn on LED connected
//to pin 4
button = true; // Set button state to true
}
// Check if the button is not pressed (digital read
//from pin 0 is LOW)
if (digitalRead(0) == 0) {
digitalWrite(4, 0); // Turn off LED connected to
//pin 4
button = false; // Set button state to false
}
// Handle different values of x received via I2C
if (x == 4) {
digitalWrite(4, 1); // Turn on LED
}
if (x == 5) {
digitalWrite(4, 0); // Turn off LED
}
if (x == 6) {
digitalWrite(4, 1); // Blink LED
delay(100);
digitalWrite(4, 0);
delay(100);
}
// Ensure LED is turned off for other values of x
else {
digitalWrite(4, 0);
}
}
// Function to handle data reception over I2C
void dato() {
// Check if there is one byte available to read
if (Wire.available() == 1) {
// Read the byte and store it in variable x
x = Wire.read();
}
}
// Function to handle data requests over I2C
void event() {
// Send 'B' if button is pressed, 'N' if button
//is not pressed
if (button) {
Wire.write("B");
} else {
Wire.write("N");
}
}