#include <Wire.h>
// Declare variables
int x = 0;
int pot = 0;
int pot_analog = 0;
int pot_led = 0;
void setup() {
// Initialize I2C communication with address 1
Wire.begin(1);
// 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 potentiometer
pinMode(0, INPUT);
}
void loop() {
delay(50); // Short delay for stability
// Read the analog value from pin 0
pot_analog = analogRead(0);
// Map the analog value to a range suitable
//for the servo (0-180)
pot = map(pot_analog, 0, 1023, 0, 180);
// Map the analog value to a range suitable
//for the LED brightness (0-255)
pot_led = map(pot_analog, 0, 1023, 0, 255);
// Write the mapped value to pin 4 to control
//LED brightness
analogWrite(4, pot_led);
}
// 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 the potentiometer value
//(mapped to servo range) over I2C
Wire.write(pot);
}