Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <driver/i2s.h>
- #include <SPIFFS.h>
- #define BUTTON_PIN 9
- // I2S pin config (verified working)
- #define I2S_BCLK 3
- #define I2S_LRC 2
- #define I2S_DOUT 10
- #define SAMPLE_RATE 8000
- #define I2S_PORT I2S_NUM_0
- void setup() {
- delay(2000);
- Serial.begin(115200);
- Serial.println("Button + WAV playback via I2S");
- pinMode(BUTTON_PIN, INPUT_PULLUP);
- if (!SPIFFS.begin()) {
- Serial.println("SPIFFS Mount Failed");
- return;
- }
- 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, // Full stereo frame
- .communication_format = I2S_COMM_FORMAT_I2S_MSB,
- .intr_alloc_flags = 0,
- .dma_buf_count = 16,
- .dma_buf_len = 128,
- .use_apll = false, // More stable on ESP32-C3
- .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
- };
- i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
- i2s_set_pin(I2S_PORT, &pin_config);
- i2s_set_clk(I2S_PORT, SAMPLE_RATE, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO);
- i2s_zero_dma_buffer(I2S_PORT);
- }
- void playWav(const char* filename) {
- File file = SPIFFS.open(filename);
- if (!file) {
- Serial.println("Failed to open WAV file");
- return;
- }
- file.seek(44); // Skip WAV header
- const size_t monoBufSize = 512;
- uint8_t buffer[monoBufSize];
- size_t bytesRead;
- while ((bytesRead = file.read(buffer, monoBufSize)) > 0) {
- int samples = bytesRead / 2;
- int16_t* stereoBuf = (int16_t*)malloc(samples * 2 * sizeof(int16_t));
- for (int i = 0; i < samples; ++i) {
- int16_t mono = ((int16_t*)buffer)[i];
- stereoBuf[2 * i] = 0; // Left muted
- stereoBuf[2 * i + 1] = mono; // Right plays audio
- }
- size_t bytesWritten;
- i2s_write(I2S_PORT, stereoBuf, samples * 4, &bytesWritten, portMAX_DELAY);
- vTaskDelay(pdMS_TO_TICKS(1));
- free(stereoBuf);
- }
- file.close();
- Serial.println("Finished playing WAV");
- }
- void loop() {
- static bool lastButtonState = HIGH;
- bool currentState = digitalRead(BUTTON_PIN);
- if (lastButtonState == HIGH && currentState == LOW) {
- Serial.println("Button pressed! Playing WAV...");
- playWav("/coin.wav");
- }
- lastButtonState = currentState;
- delay(20); // debounce
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement