AnsweredAssumed Answered

Does anybody know how to mathematically calculate blocking delays?

Question asked by arnold_w on Jun 10, 2016
Latest reply on Jun 13, 2016 by Clive One
I found a blocking delay function on the Internet ( http://thehackerworkshop.com/?p=1209 ) and I made some small changes to it:

void delay(Delay_t delay_)
{
    unsigned int loopsPerMicrosecond = (unsigned int)delay_;
    for (; 0 < delay_; delay_ --)
    {
        asm volatile
        (
            "mov r3, %[loopsPerMicrosecond] \n\t" //load the initial loop counter
            "loop4: \n\t"
                "subs r3, #1 \n\t"
                "bne loop4 \n\t"
 
            : //empty output list
            : [loopsPerMicrosecond] "r" (loopsPerMicrosecond) //input to the asm routine
            : "r3", "cc" //clobber list
        );
    }
}

Here's what the function looks like in the dump file (I don't know why it appears twice in the dump file):

void delay(Delay_t delay_)
{
    unsigned int loopsPerMicrosecond = (unsigned int)delay_;
 801a7e8:   4602        mov r2, r0
    for (; 0 < delay_; delay_ --)
 801a7ea:   b128        cbz r0, 801a7f8 <loop4+0xa>
    {
        asm volatile
 801a7ec:   4613        mov r3, r2
 
0801a7ee <loop4>:
 801a7ee:   3b01        subs    r3, #1
 801a7f0:   d1fd        bne.n   801a7ee <loop4>
 
 
void delay(Delay_t delay_)
{
    unsigned int loopsPerMicrosecond = (unsigned int)delay_;
    for (; 0 < delay_; delay_ --)
 801a7f2:   3801        subs    r0, #1
 801a7f4:   b2c0        uxtb    r0, r0
 801a7f6:   e7f8        b.n 801a7ea <delay+0x2>
            : //empty output list
            : [loopsPerMicrosecond] "r" (loopsPerMicrosecond) //input to the asm routine
            : "r3", "cc" //clobber list
        );
    }
}

I would like to find out what actual delay this function creates at different frequencies. Since I'm not used to assembler programmer language, I used an oscilloscope to measure some delays, but it's not accurate because setting the test pin low/high also takes a few instructions:

typedef enum
{
    DELAY_18_us_1_MHz_Clock             = 1,
    DELAY_32_us_1_MHz_Clock             = 2,
    DELAY_52_us_1_MHz_Clock             = 3,
    DELAY_78_us_1_MHz_Clock             = 4,
    DELAY_111_us_1_MHz_Clock            = 5,
    DELAY_150_us_1_MHz_Clock            = 6,
 
    DELAY_1_point_18_us_16_MHz_Clock    = 1,
    DELAY_12_us_16_MHz_Clock            = 7,
    DELAY_107_us_16_MHz_Clock           = 23,
    DELAY_202_us_16_MHz_Clock           = 32,
    DELAY_298_us_16_MHz_Clock           = 39,
    DELAY_312_us_16_MHz_Clock           = 40,
    DELAY_396_us_16_MHz_Clock           = 45,
    DELAY_412_us_16_MHz_Clock           = 46,
    DELAY_502_us_16_MHz_Clock           = 51,
    DELAY_604_us_16_MHz_Clock           = 56
} Delay_t;

Does anybody know a mathematical expressing for calculating the delay at various frequencies (1, 2, 4, 8, 16, ... etc MHz)?

Outcomes