#include <Wire.h>
#include <Servo.h>

const int pinLed0 = D0;
const int pinLed7 = D7;
const int pinServo = D3;

Servo myServo;
int servoPosition = 90;  // Initial servo position in degrees

void setup() {
  Wire.begin(8); // Slave 2 address
  Wire.onReceive(receiveEvent); 
  pinMode(pinLed0, OUTPUT);
  pinMode(pinLed7, OUTPUT);
  myServo.attach(pinServo);
  myServo.write(servoPosition);  // Set the initial position of the servo
}

void loop() {
  // No code needed in the loop for a slave
}

void receiveEvent(int howMany) {
  while (Wire.available()) {
    char data = Wire.read();
    
    // Control the servo and LEDs for slave 2
    if (data == 'A') {
      servoPosition = min(servoPosition + 5, 180);
      myServo.write(servoPosition);
      digitalWrite(pinLed0, HIGH);
      digitalWrite(pinLed7, LOW);
    } else if (data == 'R') {
      servoPosition = max(servoPosition - 5, 0);
      myServo.write(servoPosition);
      digitalWrite(pinLed0, LOW);
      digitalWrite(pinLed7, HIGH);
    }
  }
}