Created
November 17, 2025 11:11
-
-
Save akdeb/59295d4850342e1e1cbe89cba86e7846 to your computer and use it in GitHub Desktop.
ESP32 sine wave generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Arduino.h> | |
| #include "driver/i2s.h" | |
| // Use your existing pin defs | |
| #define I2S_LRC D0 // LRCLK / WS | |
| #define I2S_BCLK D1 // BCLK | |
| #define I2S_DOUT D2 // DIN to MAX98357A | |
| #define I2S_SD_OUT D3 // SD / shutdown (mute) pin on MAX98357A | |
| // Audio settings | |
| const int SAMPLE_RATE = 44100; // Hz | |
| const float TONE_FREQ = 440.0f; // Hz (A4) | |
| const int AMPLITUDE = 20000; // Max ~32767 for int16_t | |
| void setupI2S() { | |
| 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_ONLY_RIGHT, // mono is fine | |
| .communication_format = I2S_COMM_FORMAT_STAND_MSB, | |
| .intr_alloc_flags = 0, | |
| .dma_buf_count = 8, | |
| .dma_buf_len = 64, | |
| .use_apll = false, | |
| .tx_desc_auto_clear = true, | |
| .fixed_mclk = 0 | |
| }; | |
| i2s_pin_config_t pin_config = { | |
| .bck_io_num = I2S_BCLK, | |
| .ws_io_num = I2S_LRC, | |
| .data_out_num = I2S_DOUT, | |
| .data_in_num = I2S_PIN_NO_CHANGE | |
| }; | |
| // Install and start I2S driver | |
| i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); | |
| i2s_set_pin(I2S_NUM_0, &pin_config); | |
| i2s_set_clk(I2S_NUM_0, SAMPLE_RATE, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_MONO); | |
| } | |
| void setup() { | |
| Serial.begin(115200); | |
| delay(1000); | |
| Serial.println("Starting sine wave test..."); | |
| // Unmute MAX98357A | |
| pinMode(I2S_SD_OUT, OUTPUT); | |
| digitalWrite(I2S_SD_OUT, HIGH); | |
| setupI2S(); | |
| } | |
| void loop() { | |
| // Generate a small buffer of sine samples and send via I2S | |
| const int NUM_SAMPLES = 256; | |
| static float phase = 0.0f; | |
| const float phaseInc = 2.0f * PI * TONE_FREQ / SAMPLE_RATE; | |
| int16_t samples[NUM_SAMPLES]; | |
| for (int i = 0; i < NUM_SAMPLES; i++) { | |
| samples[i] = (int16_t)(sin(phase) * AMPLITUDE); | |
| phase += phaseInc; | |
| if (phase > 2.0f * PI) { | |
| phase -= 2.0f * PI; | |
| } | |
| } | |
| size_t bytesWritten; | |
| i2s_write(I2S_NUM_0, samples, sizeof(samples), &bytesWritten, portMAX_DELAY); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment