Issue with global variable while making 32-bit counter

前端 未结 4 615
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 06:09

I am trying to do quadrature decoding using atmel xmega avr microcontroller. Xmega has only 16-bit counters. And in addition I hav

4条回答
  •  离开以前
    2021-01-26 06:39

    The #1 fundamental embedded systems programming FAQ:

    Any variable shared between the caller and an ISR, or between different ISRs, must be protected against race conditions. To prevent some compilers from doing incorrect optimizations, such variables should also be declared as volatile.


    Those who don't understand the above are not qualified to write code containing ISRs. Or programs containing multiple processes or threads for that matter. Programmers who don't realize the above will always write very subtle, very hard-to-catch bugs.

    Some means to protect against race conditions could be one of these:

    • Temporary disabling the specific interrupt during access.
    • Temporary disabling all maskable interrupts during access (crude way).
    • Atomic access, verified in the machine code.
    • A mutex or semaphore. On single-core MCU:s where interrupts cannot be interrupted in turn, you can use a bool as "poor man's mutex".

提交回复
热议问题