Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created February 26, 2026 08:27
Show Gist options
  • Select an option

  • Save maxpromer/f328571a8c322626e638d405a6a45284 to your computer and use it in GitHub Desktop.

Select an option

Save maxpromer/f328571a8c322626e638d405a6a45284 to your computer and use it in GitHub Desktop.
#include <driver/i2s.h>
#include <math.h>
// ─── กำหนดขา I2S ───────────────────────────────────────
#define I2S_BCK_PIN 26 // Bit Clock
#define I2S_WS_PIN 25 // Word Select (LRCK)
#define I2S_DATA_PIN 22 // Data Out → DIN ของโมดูล
// ─── พารามิเตอร์เสียง ────────────────────────────────────
#define SAMPLE_RATE 44100
#define FREQUENCY 440 // ความถี่เสียง (Hz) -- A4
#define AMPLITUDE 28000 // ระดับความดัง (Max = 32767)
#define BUFFER_SIZE 256
void setup() {
Serial.begin(115200);
// ─── ตั้งค่า I2S ─────────────────────────────────────
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
.sample_rate = SAMPLE_RATE,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
.communication_format = I2S_COMM_FORMAT_STAND_I2S,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.dma_buf_count = 8,
.dma_buf_len = BUFFER_SIZE,
.use_apll = false,
.tx_desc_auto_clear = true
};
i2s_pin_config_t pin_config = {
.bck_io_num = I2S_BCK_PIN,
.ws_io_num = I2S_WS_PIN,
.data_out_num = I2S_DATA_PIN,
.data_in_num = I2S_PIN_NO_CHANGE
};
i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
i2s_set_pin(I2S_NUM_0, &pin_config);
i2s_zero_dma_buffer(I2S_NUM_0);
Serial.println("I2S Initialized — Playing Sine Wave...");
}
void loop() {
int16_t buffer[BUFFER_SIZE * 2]; // Stereo: L + R
size_t bytes_written;
for (int i = 0; i < BUFFER_SIZE; i++) {
int16_t sample = (int16_t)(AMPLITUDE * sin(2.0 * M_PI * FREQUENCY * i / SAMPLE_RATE));
buffer[i * 2] = sample; // Left Channel
buffer[i * 2 + 1] = sample; // Right Channel
}
i2s_write(I2S_NUM_0, buffer, sizeof(buffer), &bytes_written, portMAX_DELAY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment