// Define the I2S configuration
#define I2S_SAMPLE_RATE 1000 // Hz
#define I2S_BITS_PER_SAMPLE 16 // bits
#define I2S_CHANNEL_FORMAT I2S_CHANNEL_FMT_RIGHT_LEFT // stereo
#define I2S_COMM_FORMAT I2S_COMM_FORMAT_I2S_MSB // most significant bit first

// Define the analog input pin
#define ANALOG_PIN 32

// Create a buffer to store the I2S data
uint16_t buffer[2];

// Initialize the I2S driver
void i2sInit() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN),
    .sample_rate = I2S_SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE,
    .channel_format = I2S_CHANNEL_FORMAT,
    .communication_format = I2S_COMM_FORMAT,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 2,
    .dma_buf_len = 2,
    .use_apll = false,
    .tx_desc_auto_clear = false,
    .fixed_mclk = 0
  };
  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_adc_mode(ADC_UNIT_1, ANALOG_PIN);
  i2s_adc_enable(I2S_NUM_0);

  // Enable the I2S interrupt
  i2s_set_rx_intr_enable(I2S_NUM_0, I2S_INTR_RX_DONE);
}

// Read an analog value from the I2S input
uint16_t readAnalog() {
  // Read the I2S data
  i2s_read(I2S_NUM_0, buffer, sizeof(buffer), NULL, 0);

  // Return the analog value
  return buffer[0];
}

// Setup
void setup() {
  // Initialize the serial port
  Serial.begin(115200);

  // Initialize the I2S driver
  i2sInit();
}

// Loop
void loop() {
  // Read an analog value
  uint16_t value = readAnalog();

  // Print the analog value to the serial port
  Serial.println(value);

  // Wait for a millisecond
  delay(1);
}

// ISR for the I2S interrupt
void i2s_isr() {
  // Clear the interrupt flag
  i2s_clear_intr_flag(I2S_NUM_0, I2S_INTR_RX_DONE);

  // Read the I2S data
  uint16_t value = readAnalog();

  // Print the analog value to the serial port
  Serial.println(value);
}