Last active
February 9, 2025 11:19
-
-
Save GOROman/1b79fb16635881228d7f6a2156332255 to your computer and use it in GitHub Desktop.
M5Cardputer のI2Sで サイン波を鳴らすだけのコード(要電源ON)
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
// M5 Cardputer モノラルで I2S 再生 | |
#include <Arduino.h> | |
#include <driver/i2s.h> | |
#include <math.h> | |
#define SAMPLE_RATE 44100 // サンプリングレート | |
#define I2S_PORT I2S_NUM_0 | |
#define TABLE_SIZE 256 // サイン波のルックアップテーブルサイズ | |
#define I2S_BCK 41 // BCLK ピン | |
#define I2S_DATA 42 // DATA ピン | |
#define I2S_WS 43 // LRCLK ピン | |
int16_t sineWave[TABLE_SIZE]; // サイン波データ(16bit PCM) | |
void generateSineWave() { | |
for (int i = 0; i < TABLE_SIZE; i++) { | |
sineWave[i] = (int16_t)(sin(2.0 * PI * i / TABLE_SIZE) * 32767); // 16bit PCM | |
} | |
} | |
void setupI2S() { | |
i2s_config_t i2s_config = {}; // ゼロ初期化 | |
i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX); | |
i2s_config.sample_rate = SAMPLE_RATE; | |
i2s_config.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT; | |
i2s_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT; | |
i2s_config.communication_format = (i2s_comm_format_t)I2S_COMM_FORMAT_STAND_I2S; | |
i2s_config.dma_buf_count = 8; | |
i2s_config.dma_buf_len = 256; | |
i2s_config.use_apll = false; | |
i2s_config.tx_desc_auto_clear = true; | |
i2s_config.fixed_mclk = 0; | |
i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; | |
i2s_pin_config_t pin_config = {}; // ゼロ初期化 | |
pin_config.mck_io_num = I2S_PIN_NO_CHANGE; | |
pin_config.bck_io_num = I2S_BCK; | |
pin_config.ws_io_num = I2S_WS; | |
pin_config.data_out_num = I2S_DATA; | |
pin_config.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_MONO); | |
} | |
void sendSineWave() { | |
size_t bytes_written; | |
int index = 0; | |
int16_t buffer[256]; // モノラル用一時バッファ | |
while (true) { | |
for (int i = 0; i < 256; i++) { | |
buffer[i] = sineWave[index]; // モノラル出力 | |
index = (index + 1) % TABLE_SIZE; | |
} | |
i2s_write(I2S_PORT, buffer, sizeof(buffer), &bytes_written, portMAX_DELAY); | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
generateSineWave(); | |
setupI2S(); | |
Serial.println("Playing sine wave..."); | |
} | |
void loop() { | |
sendSineWave(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment