Guest User

i2s for esp32

a guest
Dec 10th, 2024
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include "driver/i2s.h"
  3. #include "driver/adc.h"
  4.  
  5. // Define I2S port and ADC configuration
  6. #define I2S_PORT I2S_NUM_0
  7. #define ADC_CHANNEL ADC1_CHANNEL_6 // GPIO34
  8.  
  9. void setup() {
  10. Serial.begin(115200);
  11. delay(100); // Allow time for Serial Monitor to initialize
  12.  
  13. Serial.println("Initializing I2S ADC...");
  14.  
  15. // Configure I2S for ADC mode
  16. i2s_config_t i2s_config = {
  17. .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN), // Master mode, RX, ADC input
  18. .sample_rate = 44100, // Sampling rate
  19. .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // 16-bit samples
  20. .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // Single channel
  21. .communication_format = I2S_COMM_FORMAT_I2S, // I2S format
  22. .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // Interrupt priority
  23. .dma_buf_count = 4, // Number of DMA buffers
  24. .dma_buf_len = 1024 // Size of each DMA buffer
  25. };
  26.  
  27. // Install I2S driver
  28. esp_err_t err = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  29. if (err != ESP_OK) {
  30. Serial.printf("I2S driver install failed: %d\n", err);
  31. return;
  32. }
  33. Serial.println("I2S driver installed successfully.");
  34.  
  35. // Configure ADC width and attenuation
  36. adc1_config_width(ADC_WIDTH_BIT_12); // 12-bit resolution
  37. adc1_config_channel_atten(ADC_CHANNEL, ADC_ATTEN_DB_6); // Attenuation for 0–2.5V range
  38. Serial.println("ADC configured successfully.");
  39.  
  40. // Set ADC mode for I2S
  41. i2s_set_adc_mode(ADC_UNIT_1, ADC_CHANNEL);
  42.  
  43. // Enable ADC mode on I2S
  44. err = i2s_adc_enable(I2S_PORT);
  45. if (err != ESP_OK) {
  46. Serial.printf("I2S ADC enable failed: %d\n", err);
  47. return;
  48. }
  49. Serial.println("I2S ADC enabled successfully.");
  50.  
  51. // Start I2S
  52. i2s_start(I2S_PORT);
  53. Serial.println("I2S started successfully.");
  54. }
  55.  
  56. void loop() {
  57. uint16_t adcBuffer[1]; // Buffer to store ADC value
  58. size_t bytesRead;
  59.  
  60. // Read data from I2S
  61. esp_err_t err = i2s_read(I2S_PORT, adcBuffer, sizeof(adcBuffer), &bytesRead, 1000 / portTICK_PERIOD_MS);
  62.  
  63. if (err != ESP_OK) {
  64. Serial.printf("I2S read failed: %d\n", err);
  65. delay(1000);
  66. return;
  67. }
  68.  
  69. if (bytesRead == 0) {
  70. Serial.println("No data read from ADC.");
  71. delay(1000);
  72. return;
  73. }
  74.  
  75. // Extract 12-bit ADC value
  76. uint16_t adcValue = adcBuffer[0] & 0xFFF;
  77.  
  78. // Print ADC value
  79. Serial.printf("ADC Value: %d\n", adcValue);
  80. delay(100); // Slow down the output for readability
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment