-->
Page 1 of 1

Unexpected behaviour of while loop

PostPosted: Sat Apr 07, 2018 7:24 am
by Alfons Mittelmeyer
When I use such a loop:

Code: Select allvolatile void ICACHE_RAM_ATTR delay_ticks(uint16_t volatile count) {
    while(count--);
}


Then it behaves as expected. It consumes an integer multiple of CPU ticks of the parameter count. It's 6 times the count.

But if I add something more to this function, then it consumes maybe 10 times the count of CPU ticks, which wouldn't matter. But then there are also additional 320 CPU ticks, which disturb me. And often when there is a while in the code, then it often consumes 320 additional CPU ticks and sometimes not. Does somebody know why and how this may be avoided.

I would like to write an exact delay function, which consumes CPU ticks.

Re: Unexpected behaviour of while loop

PostPosted: Sat Apr 07, 2018 8:14 am
by McChubby007
That is why god created the delay() function, which allows you to delay in units of actual time, millisecs. Trying to ascertain a relationship between a loop (for, while etc) and time, or even ticks is fraught and poor practice. Consider the situation where the clock speed changes? Remember the esp8266 can operate at at least two clock speeds. We don't want to regress back to the good old days of DOS games, do we?

Re: Unexpected behaviour of while loop

PostPosted: Sat Apr 07, 2018 4:14 pm
by btidey
I would agree with the sentiment that loops like this are not a great way to get delays in programs.

However, if one wants to understand what is going on then you can get an assembler dump out from the object code to see what instructions are being included.

When the code is compiled there will be a temp directory produced (typically somewhere like C:\Users\username\AppData\Local\Temp\arduino_build_69438 where username will be logged in user and the build number will change on each build.

You can temporarily copy the .o file from the sketch subfolder to where the tools, somewhere like
C:\Users\username\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2\bin

if you cd to that folder and then run xtensa-lx106-elf-objdump.exe -d test.o > test.txt where test.o is the .o file you copied.

The .txt file produced then has the dump of the code produced.