Skip to main content
Arduino

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Using millis() in unsynchronized manner

I am assuming millis() is a Timer ISR function. If so : When using millis() as mentioned in Arduino Reference : unsigned long currentMillis = millis(); What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.

Cheers and TIA

Answer*

Draft saved
Draft discarded
Cancel
5
  • 1
    Sure, a 64 bit Arduino with 2k of RAM :-) Commented Apr 30, 2021 at 17:54
  • @Edgar Bonet ,Just as an aside ( I am actually writing a millis() like function for another uC ) : Is it valid, to say , use a lock bit to prevent read while timer is updating the variable , instead of disabling the interrupt? Thanks much ! Commented May 1, 2021 at 19:57
  • 1
    @EmbSysDev: There is no need to "prevent read while timer is updating the variable": the ISR is not interruptible, so nothing can read the variable while it is being updated. You need to prevent the update while the main program is reading it. Commented May 1, 2021 at 21:33
  • @EdgarBonet: cli() disables all interrupts, so too many calls to millis() would affect all interrupt based events.Would it not be sufficient to only disable TIM0 ? In the function they don't seem to be enabling the interrupts again, is it being done elsewhere(otherwise no interrupt would be enabled).Would make sense to enable the interrupts again before exiting millis() ? Thanks for your time ! Commented May 4, 2021 at 7:11
  • 1
    @EmbSysDev: You may indeed disable selectively TIM0, although that would take a few more cycles than cli(). This critical section is very short, so globally disabling interrupts is fine here. Re "they don't seem to be enabling the interrupts again": that's what SREG = oldSREG; does: re-enable interrupts, but only if they were initially enabled when the function was called. Commented May 4, 2021 at 12:13

AltStyle によって変換されたページ (->オリジナル) /