Need to have sub microsecond delay precision
Fractional Microsecond Delay;
`FreeRtos::delay_us` will block for less than the given time for fractional milliseconds
General-Purpose Delay Provider
Hi guys,
I'm trying to implement something that will generate two triggers at regular intervals where the two triggers are separated by a configurable delay. The delay has to be configurable to sub microsecond resolution. Ideally, 500ns or less.
I chose the ESP32 because of its 240MHz clock, but it still seems to be having trouble.
I'm messing around with the following code:
#define cyclespermicro 240
#define microcycles(n) (n*cyclespermicro)
uint32_t startCounter, counter, cpu_cycles;
int cyclediff, totalcycles, corrected;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
startCounter = ESP.getCycleCount();
totalcycles = startCounter + microcycles(2);
//delayMicroseconds(1);
while (ESP.getCycleCount() < totalcycles) {
__asm__ __volatile__ ("nop");
}
counter = ESP.getCycleCount();
cpu_cycles = counter - startCounter;
corrected = cpu_cycles - 262;
Serial.print("StartCounter: ");
Serial.print(startCounter);
Serial.print(" counter: ");
Serial.print(counter);
Serial.print(" cpu_cycles: ");
Serial.print(cpu_cycles);
Serial.print(" corrected: ");
Serial.println(corrected);
}
void loop() {
}The problem is that I get the same number of clock cycles for 1 us as I do for 2 us. I'm guessing this is because the while loop overhead is overwhelming the 1 us delay.
The problem is I need to have the amount of delay configurable and I don't know the best way to do this. Anyone have any ideas how to efficiently create configurable sub-microsecond delays?
EDIT: I am also noticing, when I get rid of the while loop entirely, and just straight up copy in NOP lines, it works as expected for like 3 NOPs, but once I hit 5 NOPS, the overhead jumps to like 500 cycles. What is going on here?
Hey all, possess any of you managed to get fractional microsecond delay on the ESP8266/ESP32? I need to delay about 5.33 microseconds between setting a pin high and then back to low. I understand that delayMicroseconds mightbe close, but wanted to see if there might be something with a bit more resolution. Thanks!