cnlohr / ch32v003fun

Open source minimal stack for the ch32 line of WCH processors, including the ch32v003, a 10¢ 48 MHz RISC-V Microcontroller - as well as many other chips within the ch32v/x line.
MIT License
898 stars 142 forks source link

DelaySysTick jitter #237

Open romain145 opened 1 year ago

romain145 commented 1 year ago

DelaySysTick has jitter for specific values of 1, 2, 6, 8, 10 (tested up to 10). DelaySysTick(0) is always 292ns. DelaySysTick(1) is 292ns or 459ns. DelaySysTick(2) is 459ns or 626ns. DelaySysTick(3) is always 793ns.

I'm suspecting compiler optimization at play here. I tried forcing it to be inlined with little success.

Adding volatile changed the behaviour (2 doesn't have jitter anymore) but it still shows jitter for other values. It's also much slower, obviously...

void DelaySysTick( uint32_t n )
{
    volatile uint32_t targend = SysTick->CNT + n;
    while( ((int32_t)( SysTick->CNT - targend )) < 0 );
}
cnlohr commented 12 months ago

I believe this has to do with instruction alignment. Can you see what happens if you surround your code with option norvc?

https://github.com/cnlohr/ch32v003fun/blob/master/ch32v003fun/ch32v003fun.c#L738C20-L741C21