Microsecond or fraction of microsecond delay

User avatar
Vader_Mester
Posts: 300
Joined: Tue Dec 05, 2017 8:28 pm
Location: Hungary
Contact:

Microsecond or fraction of microsecond delay

Postby Vader_Mester » Sun Mar 11, 2018 1:44 pm

So whats the easiest way in the ESP32 to put in a delay of lets say 0.5 uSeconds?

Thanks for the answer in advance!

Vader[BEN]

Code: Select all

task_t coffeeTask()
{
	while(atWork){
		if(!xStreamBufferIsEmpty(mug)){
			coffeeDrink(mug);
		} else {
			xTaskCreate(sBrew, "brew", 9000, &mug, 1, NULL);
			xSemaphoreTake(sCoffeeRdy, portMAX_DELAY);
		}
	}
	vTaskDelete(NULL);
}

User avatar
kolban
Posts: 1683
Joined: Mon Nov 16, 2015 4:43 pm
Location: Texas, USA

Re: Microsecond or fraction of microsecond delay

Postby kolban » Sun Mar 11, 2018 5:22 pm

If this were my puzzle, I'd probably follow this line of logic.

The CPU is executing at a constant processor clock rate ... lets call it C hz. That means that it ticks at C times per second or, each clock tick is 1/C seconds. Let us now assume that 1/C is faster than the delay you want to wait. For example, 1us = 1 / 1000000 of a second = 1MHZ clock rate. So your clock processor clock should be > 1 MHZ (which it is ... don't know the exact number off the top of my head).

In ESP32 assembler, there is a special register called CCOUNT that increments (internally and in the hardware) every processor clock cycle.

What this means is that each time CCOUNT increments, we know that 1/C seconds have passed. Now you can write some code that would (loosely) do the following.

Code: Select all

function delay(period) {
   start = CCOUNT;
   while (CCOUNT - start < period) {
      // do nothing
   }
}[
This would busy wait (waste) the cycles, but it should work. You might also have to disable some of the interrupts if you need absolutely delays no matter what. For example, you may be preempted by FreeRTOS.
Free book on ESP32 available here: https://leanpub.com/kolban-ESP32

User avatar
Vader_Mester
Posts: 300
Joined: Tue Dec 05, 2017 8:28 pm
Location: Hungary
Contact:

Re: Microsecond or fraction of microsecond delay

Postby Vader_Mester » Sun Mar 11, 2018 5:49 pm

Thanks for this idea. I might check this.

Vader[BEN]

Code: Select all

task_t coffeeTask()
{
	while(atWork){
		if(!xStreamBufferIsEmpty(mug)){
			coffeeDrink(mug);
		} else {
			xTaskCreate(sBrew, "brew", 9000, &mug, 1, NULL);
			xSemaphoreTake(sCoffeeRdy, portMAX_DELAY);
		}
	}
	vTaskDelete(NULL);
}

Who is online

Users browsing this forum: Majestic-12 [Bot] and 65 guests