▲ 1 r/esp32
```
#include <driver/i2s.h>
// ===================== I2S PORTS =====================
#define I2S_A I2S_NUM_0
#define I2S_B I2S_NUM_1
// ===================== ROOM A (I2S0) =====================
#define A_BCLK 16
#define A_LRCK 15
#define A_SDIN 17
#define A_DOUT 8
// ===================== ROOM B (I2S1) =====================
#define B_BCLK 5
#define B_LRCK 4
#define B_SDIN 6
#define B_DOUT 7
// ===================== BUFFERS =====================
int16_t bufA[128];
int16_t bufB[128];
// ===================== SETUP I2S A =====================
void setupI2S_A() {
i2s_config_t configA = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_TX),
.sample_rate = 16000,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = I2S_COMM_FORMAT_I2S,
.intr_alloc_flags = 0,
.dma_buf_count = 4,
.dma_buf_len = 64,
.use_apll = false
};
i2s_pin_config_t pinsA = {
.bck_io_num = A_BCLK,
.ws_io_num = A_LRCK,
.data_out_num = A_DOUT,
.data_in_num = A_SDIN
};
i2s_driver_install(I2S_A, &configA, 0, NULL);
i2s_set_pin(I2S_A, &pinsA);
}
// ===================== SETUP I2S B =====================
void setupI2S_B() {
i2s_config_t configB = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_TX),
.sample_rate = 16000,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = I2S_COMM_FORMAT_I2S,
.intr_alloc_flags = 0,
.dma_buf_count = 4,
.dma_buf_len = 64,
.use_apll = false
};
i2s_pin_config_t pinsB = {
.bck_io_num = B_BCLK,
.ws_io_num = B_LRCK,
.data_out_num = B_DOUT,
.data_in_num = B_SDIN
};
i2s_driver_install(I2S_B, &configB, 0, NULL);
i2s_set_pin(I2S_B, &pinsB);
}
// ===================== SETUP =====================
void setup() {
Serial.begin(115200);
setupI2S_A();
setupI2S_B();
Serial.println("Dual-room intercom started");
}
// ===================== LOOP =====================
void loop() {
size_t bytesA, bytesB;
// ---------- ROOM A ----------
i2s_read(I2S_A, bufA, sizeof(bufA), &bytesA, portMAX_DELAY);
for (int i = 0; i < bytesA / 2; i++) {
bufA[i] *= 2.0; // gain
bufA[i] = constrain(bufA[i], -32768, 32767);
}
i2s_write(I2S_A, bufA, bytesA, &bytesA, portMAX_DELAY);
// ---------- ROOM B ----------
i2s_read(I2S_B, bufB, sizeof(bufB), &bytesB, portMAX_DELAY);
for (int i = 0; i < bytesB / 2; i++) {
bufB[i] *= 2.0;
bufB[i] = constrain(bufB[i], -32768, 32767);
}
i2s_write(I2S_B, bufB, bytesB, &bytesB, portMAX_DELAY);
}
```
When the gain is changed to less than or greater than 2.0, the output goes crazy. What is wrong with this code? What changes should I fix so I can change the gain with AGC.
u/AdFlaky1032 — 13 days ago