|
| 1 | +/* |
| 2 | + * This is an example to read analog data at high frequency using the I2S peripheral |
| 3 | + * Run a wire between pins 27 & 32 |
| 4 | + * The readings from the device will be 12bit (0-4096) |
| 5 | + */ |
| 6 | +#include <driver/i2s.h> |
| 7 | + |
| 8 | +#define I2S_SAMPLE_RATE 78125 |
| 9 | +#define ADC_INPUT ADC1_CHANNEL_4 //pin 32 |
| 10 | +#define OUTPUT_PIN 27 |
| 11 | +#define OUTPUT_VALUE 3800 |
| 12 | +#define READ_DELAY 10000 //microseconds |
| 13 | + |
| 14 | +void i2sInit() |
| 15 | +{ |
| 16 | + i2s_config_t i2s_config = { |
| 17 | + .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN), |
| 18 | + .sample_rate = I2S_SAMPLE_RATE, // The format of the signal using ADC_BUILT_IN |
| 19 | + .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // is fixed at 12bit, stereo, MSB |
| 20 | + .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, |
| 21 | + .communication_format = I2S_COMM_FORMAT_I2S_MSB, |
| 22 | + .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, |
| 23 | + .dma_buf_count = 4, |
| 24 | + .dma_buf_len = 8, |
| 25 | + .use_apll = false, |
| 26 | + .tx_desc_auto_clear = false, |
| 27 | + .fixed_mclk = 0 |
| 28 | + }; |
| 29 | + i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL); |
| 30 | + i2s_set_adc_mode(ADC_UNIT_1, ADC_INPUT); |
| 31 | + i2s_adc_enable(I2S_NUM_0); |
| 32 | +} |
| 33 | + |
| 34 | +void reader(void *pvParameters) { |
| 35 | + uint32_t read_counter = 0; |
| 36 | + uint64_t read_sum = 0; |
| 37 | + while(1){ |
| 38 | + size_t bytes_read = 0; |
| 39 | + uint16_t buffer = 0; |
| 40 | + i2s_read(I2S_NUM_0, &buffer, sizeof(buffer), &bytes_read, portMAX_DELAY); |
| 41 | + buffer = ~buffer; // The data is inverted |
| 42 | + //Serial.println(buffer % 0x1000); |
| 43 | + read_sum += buffer % 0x1000; // The 4 high bits are the channel |
| 44 | + read_counter++; |
| 45 | + if (bytes_read != sizeof(buffer)) Serial.println("buffer empty!"); |
| 46 | + if (read_counter == I2S_SAMPLE_RATE) { |
| 47 | + Serial.printf("avg: %d\n", read_sum/I2S_SAMPLE_RATE); |
| 48 | + read_counter = 0; |
| 49 | + read_sum = 0; |
| 50 | + i2s_adc_disable(I2S_NUM_0); |
| 51 | + delay(READ_DELAY); |
| 52 | + i2s_adc_enable(I2S_NUM_0); |
| 53 | + |
| 54 | + } |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +void setup() { |
| 59 | + Serial.begin(115200); |
| 60 | + // Put a signal out on pin |
| 61 | + uint32_t freq = ledcSetup(0, I2S_SAMPLE_RATE, 10); |
| 62 | + Serial.printf("Output frequency: %d\n", freq); |
| 63 | + ledcWrite(0, OUTPUT_VALUE/4); |
| 64 | + ledcAttachPin(OUTPUT_PIN, 0); |
| 65 | + // Initialize the I2S peripheral |
| 66 | + i2sInit(); |
| 67 | + // Create a task that will read the data |
| 68 | + xTaskCreatePinnedToCore(reader, "ADC_reader", 2048, NULL, 1, NULL, 1); |
| 69 | +} |
| 70 | + |
| 71 | +void loop() {} |
0 commit comments