Problem sampling analog audio - advice!

I have a spectrum analyzer up and working nicely on an ESP32 with a 512 LED array. You can see an early version of it running here:

Super Mega Awesome USA Color Spectrum Analyzer Video

In the sample loop, I was busy-wating with while() checking to see if the right number of microseconds had elapsed yet. That worked and usually came out reasonably close to the "predicted" amount of time it should take. I print the predicted and actual amount of time taken to the serial port.

I thought it'd be cleaner to just call ets_delay_us(_sampling_period_us) since that does literally what I was trying to do. But the debug code shows it taking 3X as long as expected now, like the ets_delay_us function has a lot of overhead or latency. It's also not especially regular from one call to the next.

I can go back to the while() approach, but I thought this -should- work. Anyone know why it doesn't?

Any other tips for sampling audio on the ESP32 (particularly setting up the ADC passes and filters!) would be welcome... here's my code.

		#if SHOW_SAMPLE_TIMING
		float expectedTime = SAMPLES * _sampling_period_us;
		unsigned long startTime = micros();
		#endif

		for (int i = 0; i < SAMPLES; i++)
		{
			_vImaginary[i] = 0;
			_vReal[i] = analogRead(_inputPin);
			ets_delay_us(_sampling_period_us);
		}

		#if SHOW_SAMPLE_TIMING
		Serial.printf("Sampling took %5ld us and was expedcted to take %5ld\n", micros() - startTime, (unsigned long)expectedTime);
		#endif

But the debug code shows it taking 3X as long as expected now, like the ets_delay_us function has a lot of overhead or latency.

As we have no clue what value _sampling_period_us has, we cannot really help. But in your calculation you completely forgot that analogRead also needs some time to do it's job (somewhere around 120µs on an AVR).

Actual answer: portDISABLE_INTERRUPTS