Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include "driver/i2s.h"
- #include "driver/adc.h"
- // Define I2S port and ADC configuration
- #define I2S_PORT I2S_NUM_0
- #define ADC_CHANNEL ADC1_CHANNEL_6 // GPIO34
- void setup() {
- Serial.begin(115200);
- delay(100); // Allow time for Serial Monitor to initialize
- Serial.println("Initializing I2S ADC...");
- // Configure I2S for ADC mode
- i2s_config_t i2s_config = {
- .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN), // Master mode, RX, ADC input
- .sample_rate = 44100, // Sampling rate
- .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // 16-bit samples
- .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // Single channel
- .communication_format = I2S_COMM_FORMAT_I2S, // I2S format
- .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // Interrupt priority
- .dma_buf_count = 4, // Number of DMA buffers
- .dma_buf_len = 1024 // Size of each DMA buffer
- };
- // Install I2S driver
- esp_err_t err = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
- if (err != ESP_OK) {
- Serial.printf("I2S driver install failed: %d\n", err);
- return;
- }
- Serial.println("I2S driver installed successfully.");
- // Configure ADC width and attenuation
- adc1_config_width(ADC_WIDTH_BIT_12); // 12-bit resolution
- adc1_config_channel_atten(ADC_CHANNEL, ADC_ATTEN_DB_6); // Attenuation for 0–2.5V range
- Serial.println("ADC configured successfully.");
- // Set ADC mode for I2S
- i2s_set_adc_mode(ADC_UNIT_1, ADC_CHANNEL);
- // Enable ADC mode on I2S
- err = i2s_adc_enable(I2S_PORT);
- if (err != ESP_OK) {
- Serial.printf("I2S ADC enable failed: %d\n", err);
- return;
- }
- Serial.println("I2S ADC enabled successfully.");
- // Start I2S
- i2s_start(I2S_PORT);
- Serial.println("I2S started successfully.");
- }
- void loop() {
- uint16_t adcBuffer[1]; // Buffer to store ADC value
- size_t bytesRead;
- // Read data from I2S
- esp_err_t err = i2s_read(I2S_PORT, adcBuffer, sizeof(adcBuffer), &bytesRead, 1000 / portTICK_PERIOD_MS);
- if (err != ESP_OK) {
- Serial.printf("I2S read failed: %d\n", err);
- delay(1000);
- return;
- }
- if (bytesRead == 0) {
- Serial.println("No data read from ADC.");
- delay(1000);
- return;
- }
- // Extract 12-bit ADC value
- uint16_t adcValue = adcBuffer[0] & 0xFFF;
- // Print ADC value
- Serial.printf("ADC Value: %d\n", adcValue);
- delay(100); // Slow down the output for readability
- }
Advertisement
Add Comment
Please, Sign In to add comment