#include <Arduino.h>
#include <Wire.h>

#define DEVICE_ADDRESS 0x50

// Virtual hardware registers
uint8_t reg_INA = 0;
uint8_t reg_INB = 0;
uint8_t reg_pointer = 0;  // acts as address register for reads



// Called when master writes data
void receiveEvent(int howMany) {
  if (howMany < 1) return;

  // First byte is always register address
  reg_pointer = Wire.read();
  howMany--;

  if (howMany == 1) {
    // Second byte is data to write
    uint8_t value = Wire.read();
    if (reg_pointer == 0x21) {
      reg_INA = value;
      Serial.println("INA set");
    } else if (reg_pointer == 0x22) {
      reg_INB = value;
      Serial.println("INB set");
    } else {
      // Writes to read-only registers are ignored
      Serial.println("Write to read-only register ignored");
    }
  }
}

// Called when master reads data
void requestEvent() {
  uint8_t value = 0;

  switch (reg_pointer) {
    case 0x21: value = reg_INA; break;
    case 0x22: value = reg_INB; break;
    case 0x23: value = min(reg_INA, reg_INB); break;
    case 0x24: value = max(reg_INA, reg_INB); break;
    default: value = 0xFF; break; // undefined register
  }

  Wire.write(value);
}

void setup() {
  Wire.begin(DEVICE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
}

void loop() {
}