Skip to content

Difference between two consecutive micros() can be negative if interrupts are disabled. #2087

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ArminJo opened this issue Aug 1, 2023 · 1 comment
Labels
invalid This doesn't seem right

Comments

@ArminJo
Copy link

ArminJo commented Aug 1, 2023

Describe the bug

It is like #1680, and the current implementation still has this problem described by matthijskooijman:

uint32_t getCurrentMicros(void)
{
  uint32_t m0 = HAL_GetTick();
  __IO uint32_t u0 = SysTick->VAL;
  uint32_t m1 = HAL_GetTick();
  __IO uint32_t u1 = SysTick->VAL;
  const uint32_t tms = SysTick->LOAD + 1;

  if (m1 != m0) {
    return (m1 * 1000 + ((tms - u1) * 1000) / tms);
  } else {
    return (m0 * 1000 + ((tms - u0) * 1000) / tms);
  }
}

To Reproduce

This error leads to Arduino-IRremote/Arduino-IRremote#1152, which can easily reproduced by compiling the SendDemo example of IRRemote library version 4.1.0. After a few seconds, IR output signal generation stops (as expected since I analyzed this bug 😞 ).
Deactivating the disable of the interrupt statement noInterrupts(); in IRSend.hpp near line 1044 fixes the error.

Expected behavior

When calling micros() twice, the second call should always return equal or more than the first call.

Solutions

I have no idea for an solution, but it should at least be documented in the code, to avoid long investigations.

@fpistm
Copy link
Member

fpistm commented Aug 4, 2023

Hi @ArminJo
micros() relies on systick interrupt. If you disable the interrupt, systick is no more incremented.
If you really need to disable interrupt you can try to use delayMicrosecond which uses DWT free running counter, so instead of compute time manually simply wait the request time.
Or as you do do not disable interrupt.

The point you mention from @matthijskooijman is not the same than here.So, unfortunately, I can't do nothing for your issue as if you disable interrupt you freeze the tick.

@fpistm fpistm closed this as completed Aug 4, 2023
@fpistm fpistm added the invalid This doesn't seem right label Aug 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
invalid This doesn't seem right
Projects
None yet
Development

No branches or pull requests

2 participants