Skip to content

Commit fa6f759

Browse files
lbernstoneme-no-dev
authored andcommitted
I2s adc (#2309)
* An example to read high frequency analog data using i2s_adc * HiFreq_ADC.ino
1 parent 6718da0 commit fa6f759

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

Diff for: libraries/ESP32/examples/I2S/HiFreq_ADC/HiFreq_ADC.ino

+25-13
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
/*
22
* This is an example to read analog data at high frequency using the I2S peripheral
33
* Run a wire between pins 27 & 32
4-
* The readings from the device will be 12bit (0-4096)
4+
* The readings from the device will be 12bit (0-4096)
55
*/
66
#include <driver/i2s.h>
77

88
#define I2S_SAMPLE_RATE 78125
99
#define ADC_INPUT ADC1_CHANNEL_4 //pin 32
1010
#define OUTPUT_PIN 27
1111
#define OUTPUT_VALUE 3800
12-
#define READ_DELAY 10000 //microseconds
12+
#define READ_DELAY 9000 //microseconds
13+
14+
uint16_t adc_reading;
1315

1416
void i2sInit()
1517
{
@@ -34,23 +36,29 @@ void i2sInit()
3436
void reader(void *pvParameters) {
3537
uint32_t read_counter = 0;
3638
uint64_t read_sum = 0;
39+
// The 4 high bits are the channel, and the data is inverted
40+
uint16_t offset = (int)ADC_INPUT * 0x1000 + 0xFFF;
41+
size_t bytes_read;
3742
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!");
43+
uint16_t buffer[2] = {0};
44+
i2s_read(I2S_NUM_0, &buffer, sizeof(buffer), &bytes_read, 15);
45+
//Serial.printf("%d %d\n", offset - buffer[0], offset - buffer[1]);
46+
if (bytes_read == sizeof(buffer)) {
47+
read_sum += offset - buffer[0];
48+
read_sum += offset - buffer[1];
49+
read_counter++;
50+
} else {
51+
Serial.println("buffer empty");
52+
}
4653
if (read_counter == I2S_SAMPLE_RATE) {
47-
Serial.printf("avg: %d\n", read_sum/I2S_SAMPLE_RATE);
54+
adc_reading = read_sum / I2S_SAMPLE_RATE / 2;
55+
//Serial.printf("avg: %d millis: ", adc_reading);
56+
//Serial.println(millis());
4857
read_counter = 0;
4958
read_sum = 0;
5059
i2s_adc_disable(I2S_NUM_0);
5160
delay(READ_DELAY);
5261
i2s_adc_enable(I2S_NUM_0);
53-
5462
}
5563
}
5664
}
@@ -68,4 +76,8 @@ void setup() {
6876
xTaskCreatePinnedToCore(reader, "ADC_reader", 2048, NULL, 1, NULL, 1);
6977
}
7078

71-
void loop() {}
79+
void loop() {
80+
delay(1020);
81+
Serial.printf("ADC reading: %d\n", adc_reading);
82+
delay(READ_DELAY);
83+
}

0 commit comments

Comments
 (0)